<?php
namespace pad;

require_once 'app.php';

// 报工端基类
class indexClass
{
    use app;

	/*属性*/
	public        $powerAll     = "";                    //系统权限目录
	public array  $control;                              //当前登录者
	public array  $controlJob;                           //当前登录者职位
	public        $controlPower = [];                    //当前登录者权限
	public string $warn;                                 //提示

	public static        $user      = []; //用户
	public static        $stid;
	public static        $staff     = [];
	public static        $warehouse = [];
    public static        $publicSettings = [];
	public string        $root;
	public static string $coid;
	public const baseUnit = 100;//金额以分为单位是将除以此基础值
    public        $config = ['dispatch'=>'生产派工','workReport'=>'生产报工',];


	/*构造函数*/
	public function __construct()
	{
		// 启用扩展
		$this->init();
		//获得全局函数
		$this->powerAll = $GLOBALS['powerAll'];
		$this->root     = root;

        // 用于接口调用后端函数
        if (!empty($this->header['Auth'])) {
            return;
        }

		//登录验证
		if (empty($_SESSION['stid'])) {
			$this->warn = "你未登录";
		} elseif ($this->get('cla') == "login" and $this->get('fun') == "out") {
			unset($_SESSION['stid']);
			$_SESSION['warn'] = "你已经退出管理员登录状态";
			header("Location:{$this->root}pad/index.html?cla=login");
			exit();
		} else {
			$this->control = query("staff", "stid = '$_SESSION[stid]'");
			if ($this->control['stid'] != $_SESSION['stid']) {
				$this->warn = "未找到你的登录账号";
			} else {
				self::$stid = $this->control['stid'];
				self::$user = query('user', " stid = '" . self::$stid . "' ");
				// 登录限制
				if ($_SESSION['deviceId'] != self::$user['deviceId'] && para('adLoginMultiDeviceLimit') == '开') {
					unset($_SESSION['stid'], $_SESSION['deviceId']);
					$_SESSION['warn'] = "您的账号在另一处登录，您已被迫下线";
					echo exit("<script>top.location.href = root+'pad/index.html?cla=login'</script>");
				}
				$this->controlJob   = query("job", " id = '" . $this->control['jobId'] . "' ");
				self::$staff        = $this->control;
				$this->controlPower = self::getUserPower();
				//设置coid
                if(isset($_SESSION['coid'])){
                    self::updateCoidRecord($_SESSION['coid']);
                    self::$coid = $_SESSION['coid'];
                    unset($_SESSION['coid']);
                }else {
                    self::$coid = self::findCoid();
                }
				//查询管理的仓库
				$warehouse       = find(['table' => 'warehouse', 'field' => 'id', 'where' => " coid = '" . self::$coid . "' and (member like '%" . self::$stid . "%' or member is null) and state = '启用' "]);
				self::$warehouse = static::isNull($warehouse['array']) ? [] : array_column($warehouse['array'], 'id');
                //获取公共选项设置
                self::$publicSettings = self::findOptionSetting();
				$loginPage       = static::rGet(self::$user['uid'] . 'loginPage');
				if ($loginPage == 1) {
					//登录成功时检查是否设置了默认值
					//$this->insertDefault();
					//给用户设置默认查看的统计图表设置
					//$this->setDefaultSetting();
					static::rSet('loginPage', 0);
				}
			}
		}
	}

	/**
	 * 导入模板菜单
	 *
	 * @return string[][]
	 */
	protected function importTemplateField(): array
	{
		return [
			'人力资源' => [
				'组织架构' => [
					'员工档案',
					'职位',
				],
				'招聘'     => [
					'人才库',
				],
				'考试'     => [
					'题库管理',
				],
				'绩效'     => [
					'绩效目标',
				],
				'考勤'     => [
					'考勤记录',
				],
				'薪酬'     => [
					'社保核算',
					'个税核算',
				],
				'劳务派遣' => [
					'派遣单位',
					'劳动报酬清单',
				],
			],
			'行政管理' => [
				'物资'   => [
					'物资档案',
				],
				'车辆'   => [
					'驾驶员',
					'车辆档案',
				],
				'会议室' => [
					'会议室档案',
				],
				'档案'   => [
					'档案管理',
				],
				'访客'   => [
					'来访登记',
				],
			],
			'客户管理' => [
				'线索' => [
					'线索',
					'线索池',
				],
				'客户' => [
					'客户',
					'公客池',
					'联系人',
				],
				'商机' => [
					'商机',
				],
			],
			'供应链'   => [
				'物流' => [
					'驾驶员档案',
					'内部车辆',
				],
				'库存' => [
					'盘点单',
				],
				'资料' => [
					'物料档案',
					'客户档案',
					'客户价格本',
					'供应商',
					'物料清单',
					'仓库',
					'库存期初',
					'客户期初',
					'供应商期初',
				],
			],
			'生产制造' => [
				'生产控制' => [
					'车间考勤表',
					'计时日报',
				],
				'设备'     => [
					'配件',
				],
				'模具'     => [
					'模具',
				],
				'基础数据' => [
					'生产线档案',
					'工序档案',
				],
			],
			'财务会计' => [
				'凭证'     => [
					'查凭证',
				],
				'资金'     => [
					'现金日记账',
					'银行日记账',
					'内部转账',
				],
				'固定资产' => [
					'资产登记',
				],
				'发票'     => [
					'销项发票',
					'进项发票',
				],
				'设置'     => [
					'科目',
					'期初',
					'项目',
				],
			],
		];
	}

	/**
	 * 生成默认值
	 */
	protected function insertDefault()
	{
		global $powerAll;
		//生成默认仓库分类
		if (static::total(array('table' => 'warehouse_type', 'where' => "coid = '" . self::$coid . "'")) == 0) {
			//默认档案分类
			static::insert(array(
				'table' => 'warehouse_type',
				'field' => [
					'id'   => self::getId(),
					'coid' => self::$coid,
					'name' => '默认分类',
					'pid'  => 0,
					'list' => 1,
				],
			));
		}
		//生成本位币
		if (static::total(array('table' => 'currency', 'where' => "isBase = '是' and coid = '" . self::$coid . "'")) == 0) {
			static::insert(array(
				'table' => 'currency',
				'field' => [
					'id'     => self::getId(),
					'coid'   => self::$coid,
					'name'   => '人民币',
					'isBase' => '是',
					'code'   => 'CNY',
					'rate'   => 1,
				],
			));
		}
		//判断当前超级管理员是否有人才库信息，没有则生成一个，不然不能更新管理员信息
		$userAll = find(array('table' => 'user', 'where' => "isDel = 1"));
		foreach ($userAll['array'] as $array) {
			$staff = query('staff', "stid = '$array[stid]'");
			if (static::total(array('table' => 'talent_pool', 'where' => "id = '$staff[talentId]'")) == 0) {
				$talentId = self::getId();
				static::insert(array(
					'table' => 'talent_pool',
					'field' => [
						'id'       => $talentId,
						'name'     => $staff['name'],
						'tel'      => $staff['tel'],
						'state'    => '人才登记',
						'workFlow' => 2,
					],
				));
				static::update(
					array('table' => 'staff', 'field' => ['talentId' => $talentId], 'where' => "stid = '$staff[stid]'")
				);
			}
		}
		//生成默认档案库位
		if (static::total(array('table' => 'archive_cabinet', 'where' => "isDefault = 1")) == 0) {
			//默认档案库位
			static::insert(array(
				'table' => 'archive_cabinet',
				'field' => [
					'id'        => self::getId(),
					'name'      => '默认库位',
					'isDefault' => 1,
					'list'      => 1,
				],
			));
		}
        //生成默认档案分类
		if (static::total(array('table' => 'archive_type', 'where' => "isDefault = 1")) == 0) {
			//默认档案分类
			static::insert(array(
				'table' => 'archive_type',
				'field' => [
					'id'        => self::getId(),
					'name'      => '默认分类',
					'isDefault' => 1,
					'list'      => 1,
				],
			));
		}
		if (static::total(array('table' => 'pool', 'where' => "id = 'defaultPool'")) == 0) {
			//默认线索池
			static::insert(array(
				'table' => 'pool',
				'field' => [
					'id'          => 'defaultPool',
					'type'        => '线索池',
					'name'        => '默认线索池',
					'manager'     => 'Ore126054470Vd',
					'isCooper'    => 1,
					'isSee'       => 0,
					'maxNum'      => 0,
					'frequency'   => 0,
					'limitMinute' => -1,
					'recycling'   => -1,
					'remindDay'   => 0,
					'stid'        => 'Ore126054470Vd',
				],
			));
		}
		if (static::total(array('table' => 'pool', 'where' => "id = 'defaultClientPool'")) == 0) {
			//默认公客池
			static::insert(array(
				'table' => 'pool',
				'field' => [
					'id'          => 'defaultClientPool',
					'type'        => '公客池',
					'name'        => '默认客户池',
					'manager'     => 'Ore126054470Vd',
					'isCooper'    => 1,
					'isSee'       => 0,
					'maxNum'      => 0,
					'frequency'   => 0,
					'limitMinute' => -1,
					'recycling'   => -1,
					'remindDay'   => 0,
					'stid'        => 'Ore126054470Vd',
				],
			));
		}
        //生成物料默认属性
        if (static::total(array('table' => 'material_attr', 'where' => "name = '默认属性' and coid = '" . self::$coid . "'")) == 0) {
            //默认物料属性
            $id = self::getId();
            static::insert(array(
                'table' => 'material_attr',
                'field' => [
                    'id'   => $id,
                    'coid' => self::$coid,
                    'name' => '默认属性',
                    'stid' => 'Ore126054470Vd',
                ],
            ));
            $detailId = self::getId();
            static::insert(array(
                'table' => 'material_attr_detail',
                'field' => [
                    'id'      => $detailId,
                    'coid'    => self::$coid,
                    'orderId' => $id,
                    'value'   => '默认',
                ],
            ));
            static::insert(array(
                'table' => 'material_attr_scheme',
                'field' => [
                    'id'      => self::getId(),
                    'coid'    => self::$coid,
                    'name'    => '默认方案',
                    'content' => json_encode([$id=>[$detailId]],320),
                    'stid'    => self::$stid,
                ],
            ));

        }
		$accountRule = companyClass::returnRule(1);
		//生成初始科目
		if (static::total(array('table' => 'subject', 'where' => "coid = '" . self::$coid . "'")) == 0) {
			$all = find(array('table' => 'subject_demo', 'where' => "level = 1 and accountRule = '$accountRule' order by list asc"));
			foreach ($all['array'] as $array) {
				$id = suiji();
				static::insert(array(
					'table' => 'subject',
					'field' => [
						'id'                 => $id,
						'coid'               => self::$coid,
						'type'               => $array['type'],
						'code'               => $array['code'],
						'name'               => $array['name'],
						'direction'          => $array['direction'],
						'pid'                => '0',
						'state'              => $array['state'],
						'numAccount'         => $array['numAccount'],
						'assistAccount'      => $array['assistAccount'],
						'currencyAccount'    => $array['currencyAccount'],
						'numAccountText'     => $array['numAccountText'],
						'assistAccountIds'   => $array['assistAccountIds'],
						'currencyAccountIds' => $array['currencyAccountIds'],
						'subjectSign'        => $array['subjectSign'],
						'list'               => $array['list'],
						'selfIndex'          => $array['selfIndex'],
						'level'              => $array['level'],
						'pinyin'             => $array['pinyin'],
						'isDel'              => 0,
					],
				));
				$this->insertSubjectChild($array['id'], $id, $accountRule);
			}
		}

		//生成现金流量表
		if (static::total(array('table' => 'cash', 'where' => "coid = '" . self::$coid . "'")) == 0) {
			$all = find(array('table' => 'cash_demo', 'where' => "accountRule='$accountRule' order by code asc"));
			foreach ($all['array'] as $array) {
				static::insert(array(
					'table' => 'cash',
					'field' => [
						'id'     => suiji(),
						'coid'   => self::$coid,
						'code'   => $array['code'],
						'pinyin' => $array['pinyin'],
						'name'   => $array['name'],
						'type'   => $array['type'],
						'text'   => $array['text'],
					],
				));
			}
		}

		//生成凭证字
		if (static::total(array('table' => 'voucher_word', 'where' => "coid = '" . self::$coid . "'")) == 0) {
			$all = find(array('table' => 'voucher_word_demo', 'where' => "1=1 order by time asc"));
			foreach ($all['array'] as $k => $array) {
				static::insert(array(
					'table' => 'voucher_word',
					'field' => [
						'id'        => suiji(),
						'coid'      => self::$coid,
						'word'      => $array['word'],
						'title'     => $array['title'],
						'isDefault' => $array['isDefault'],
						'isDel'     => $array['isDel'],
					],
				));
			}
		}


		$all = find(array('table' => 'asset_debt_formula', 'where' => "coid = '" . self::$coid . "'  order by list asc"));
		foreach ($all['array'] as $array) {
			$subject = query('subject', "id = '$array[subjectId]'");
			if (empty($subject['id'])) {
				delete(array('table' => 'asset_debt_formula', 'where' => "coid = '" . self::$coid . "'"));
				delete(array('table' => 'asset_debt', 'where' => "coid = '" . self::$coid . "'"));
				delete(array('table' => 'profit_income_formula', 'where' => "coid = '" . self::$coid . "'"));
				delete(array('table' => 'profit_income', 'where' => "coid = '" . self::$coid . "'"));
				break;
			}
		}
		//生成资产负债表
		if (static::total(array('table' => 'asset_debt', 'where' => "coid = '" . self::$coid . "'")) == 0) {
			$all = find(array('table' => 'asset_debt_demo', 'where' => "accountRule='$accountRule' order by list asc"));
			foreach ($all['array'] as $k => $array) {
				static::insert(array(
					'table' => 'asset_debt',
					'field' => [
						'id'        => suiji(),
						'coid'      => self::$coid,
						'type'      => $array['type'],
						'name'      => $array['name'],
						'pid'       => $array['pid'],
						'direction' => $array['direction'],
						'list'      => $array['list'],
					],
				));
			}
			$all = find(array('table' => 'asset_debt_formula_demo', 'where' => "accountRule='$accountRule' order by list asc"));
			foreach ($all['array'] as $array) {
				$subject = query('subject', "coid = '" . self::$coid . "' and code = '$array[subjectCode]'");
				static::insert(array(
					'table' => 'asset_debt_formula',
					'field' => [
						'id'        => suiji(),
						'coid'      => self::$coid,
						'name'      => $array['name'],
						'symbol'    => $array['symbol'],
						'subjectId' => $subject['id'],
						'rule'      => $array['rule'],
					],
				));
			}
		}

		//生成利润表
		if (static::total(array('table' => 'profit_income', 'where' => "coid = '" . self::$coid . "'")) == 0) {
			$all = find(array('table' => 'profit_income_demo', 'where' => "accountRule='$accountRule' order by list asc"));
			foreach ($all['array'] as $array) {
				static::insert(array(
					'table' => 'profit_income',
					'field' => [
						'id'    => suiji(),
						'coid'  => self::$coid,
						'title' => $array['title'],
						'type'  => $array['type'],
						'name'  => $array['name'],
						'pid'   => $array['pid'],
					],
				));
			}
			$all = find(array('table' => 'profit_income_formula_demo', 'where' => "accountRule='$accountRule'"));
			foreach ($all['array'] as $array) {
				$subject = query('subject', "coid = '" . self::$coid . "' and code = '$array[subjectCode]'");
				static::insert(array(
					'table' => 'profit_income_formula',
					'field' => [
						'id'        => suiji(),
						'coid'      => self::$coid,
						'name'      => $array['name'],
						'symbol'    => $array['symbol'],
						'subjectId' => $subject['id'],
						'rule'      => $array['rule'],
					],
				));
			}
		}

		if (static::total(array('table' => 'period_end_setting', 'where' => "coid = '" . self::$coid . "'")) == 0) {
			//生成预设凭证模板
			$all = find(array('table' => 'period_end_setting_demo','where'=>"accountRule='$accountRule'"));
			foreach ($all['array'] as $array) {
				$id           = suiji();
				$voucher_word = query('voucher_word', "coid = '" . self::$coid . "' and word = '$array[voucherWord]'");
				static::insert(array(
					'table' => 'period_end_setting',
					'field' => [
						'id'            => $id,
						'coid'          => self::$coid,
						'name'          => $array['name'],
						'type'          => $array['type'],
						'voucherWord'   => $array['voucherWord'],
						'voucherWordId' => $voucher_word['id'],
						'isDel'         => 0,
					],
				));
				$children = find(array('table' => 'period_end_setting_detail_demo', 'where' => "orderId = '$array[id]' and accountRule='$accountRule' order by list asc"));
				foreach ($children['array'] as $item) {
					$childSubject = query('subject', "coid = '" . self::$coid . "'  and code = '" . $item['subjectCode'] . "'");
					static::insert(array(
						'table' => 'period_end_setting_detail',
						'field' => [
							'id'        => suiji(),
							'coid'      => self::$coid,
							'orderId'   => $id,
							'summary'   => $item['summary'],
							'subjectId' => $childSubject['id'],
							'rule'      => $item['rule'],
							'direction' => $item['direction'],
						],
					));
				}
			}
		}
		$company = query('company', "coid = '" . self::$coid . "'");
		//生成预设会计电子档案文件夹
		if (static::total(array('table' => 'account_elect_file', 'where' => "coid = '" . self::$coid . "' and name = '财务归档'")) == 0) {
			$folderId = suiji();
			static::insert(array(
				'table' => 'account_elect_file',
				'field' => [
					'id'   => $folderId,
					'pid'  => '1',
					'coid' => self::$coid,
					'type' => 'folder',
					'name' => '财务归档',
					'stid' => self::$stid,
				],
			));
			static::insert(array(
				'table' => 'account_elect_file',
				'field' => [
					'id'   => suiji(),
					'pid'  => $folderId,
					'coid' => self::$coid,
					'type' => 'folder',
					'name' => $company['name'],
					'stid' => self::$stid,
				],
			));
		}
	}

	/**
	 * 生成子科目
	 */
	private function insertSubjectChild($pid, $newId, $accountRule)
	{
		$all = find(array('table' => 'subject_demo', 'where' => "pid = '$pid' and accountRule = '$accountRule' order by selfIndex"));
		foreach ($all['array'] as $array) {
			$id = suiji();
			static::insert(array(
				'table' => 'subject',
				'field' => [
					'id'                 => $id,
					'coid'               => self::$coid,
					'type'               => $array['type'],
					'code'               => $array['code'],
					'name'               => $array['name'],
					'direction'          => $array['direction'],
					'pid'                => $newId,
					'state'              => $array['state'],
					'numAccount'         => $array['numAccount'],
					'assistAccount'      => $array['assistAccount'],
					'currencyAccount'    => $array['currencyAccount'],
					'numAccountText'     => $array['numAccountText'],
					'assistAccountIds'   => $array['assistAccountIds'],
					'currencyAccountIds' => $array['currencyAccountIds'],
					'pinyin'             => $array['pinyin'],
					'list'               => $array['list'],
					'selfIndex'          => $array['selfIndex'],
					'level'              => $array['level'],
					'isDel'              => 0,
				],
			));
			$this->insertSubjectChild($array['id'], $id, $accountRule);
		}
	}

	/**
	 * 给个人用户设置默认设置
	 */
	private function setDefaultSetting()
	{
		//生成OA小程序销售设置
		if (static::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = 'OA通知设置'")
			) == 0) {
			insert(array(
				'table' => 'user_setting',
				'field' => [
					'stid'  => self::$stid,
					'type'  => 'OA通知设置',
					'value' => json_encode(['message' => 1], 320),
				],
			));
		}

		//判断是否有销售过程统计设置
		if (static::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '销售过程统计'")
			) == 0) {
			insert(array(
				'table' => 'user_setting',
				'field' => [
					'stid'  => self::$stid,
					'type'  => '销售过程统计',
					'value' => json_encode(
						["board", "follow_client", "sale_funnel", "follow_type", "follow_rank", "visit_rank"],
						320
					),
				],
			));
		}
		//判断是否有销售业绩统计设置
		if (static::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '销售业绩统计'")
			) == 0) {
			insert(array(
				'table' => 'user_setting',
				'field' => [
					'stid'  => self::$stid,
					'type'  => '销售业绩统计',
					'value' => json_encode(
						[
							"board",
							"performance_goals",
							"payment",
							"contract_money",
							"kpi_analysis",
							"losing_analysis",
							"sign_ranking",
							"goal_achievement",
						],
						320
					),
				],
			));
		}
		//判断是否有客户分析设置
		if (static::total(array('table' => 'user_setting', 'where' => "stid = '" . self::$stid . "' and type = '客户分析'")
			) == 0) {
			insert(array(
				'table' => 'user_setting',
				'field' => [
					'stid'  => self::$stid,
					'type'  => '客户分析',
					'value' => json_encode(
						[
							"geographical",
							"industry_scale",
							"status_funnel",
							"channel_analysis",
							"customer_add",
							"customer_ranking",
							"conversion_rate",
						],
						320
					),
				],
			));
		}
	}

	/** 获取仓库查询条件
	 *
	 * @param string $field
	 * @return mixed
	 */
	public static function getWarehouseSql($field = 'id'): mixed
	{
		$sql = " and $field in ('" . implode("','", self::$warehouse) . "') ";
		return $sql;
	}

    /**
     * 获取选项设置
     * @param $type
     * @return array
     */
    public static function getSettingPad($type): array
    {
        $settingInfo = query('option_setting', "type = '$type' and coid = '" . self::$coid . "'");
        $setting = json_decode($settingInfo['setting'], true);
        if (!$settingInfo['id'] || !$setting || !is_array($setting)) {
            return [];
        } else {
            return $setting;
        }
    }

    /**
     * 查找公共设置
     *
     * @return mixed
     */
    public static function findOptionSetting(): mixed
    {
        $publicSettings = self::getSettingPad('公共');
        if (empty($publicSettings)) {
            //公共设置数组
            $setting = [
                '公共'=>[
                    'lossRate' => '2',
                    'batchCtrl' => [
                        'auto' => '1',
                        'option' => '1',
                        'period' => '1',
                    ],
                    'barcodeCtrl' => [
                        'merge' => 0,
                        'option' => 0,
                    ],
                    'invoicePrice' => 0,
                    'materialCode' => 0,
                    'materialRate' => 0,
                    'materialStop' => 0,
                    'numPrecision' => [
                        'num' => '2',
                        'numLostZero' => '1',
                    ],
                    'quoteWithTax' => 0,
                    'companyCanStop' => '1',
                    'conversionRate' => 0,
                    'pricePrecision' => [
                        'num' => '4',
                        'priceLostZero' => '1',
                    ],
                    'showBomCatalog' => '1',
                    'depreciationrate' => 0,
                    'companyRepeatCtrl' => '提示',
                    'materialRepeatDeal' => [
                        'method' => 'ban',
                        'option' => 0,
                    ],
                    'companyRepeatItemCtrl' => [
                        'companyName',
                        'contactTel',
                    ],
                ],
                '销售'=>[
                    'autoOut' => 0,
                    'ctrlSale' => 0,
                    'ctrlUnit' => 0,
                    'creditCtrl' => [
                        'way' => '保存',
                        'option' => 0,
                        'saleMoney' => '1',
                        'bookingMoney' => '1',
                    ],
                    'saleStrict' => 0,
                    'checkRepeat' => 0,
                    'quoteWithTax' => 0,
                    'salePriceCtrl' => [
                        'way' => '',
                        'method' => '',
                        'option' => 0,
                    ],
                    'saleWithOrder' => 0,
                    'machiningStrick' => 0,
                    'refundWithOrder' => 0,
                ],
                '采购'=>[
                    'checkRepeat' => 0,
                    'refundOrder' => 0,
                    'purchaseAutoIn' => 0,
                    'purchaseStrict' => 0,
                    'purchaseMustOrder' => 0,
                    'purchasePriceCtrl' => [
                        'way' => '',
                        'method' => '',
                        'option' => 0,
                    ],
                    'purchaseApplyStrict' => 0,
                    'purchaseBaseWithTax' => 0,
                ],
                '委外'=>[
                    'reverseCheck' => 0,
                    'bomShowMethod' => 0,
                    'allowNewMaterial' => 0,
                    'outsourceTaxPrice' => 0,
                    'outsourcePriceCtrl' => [
                        'way' => '',
                        'method' => '',
                        'option' => 0,
                    ],
                    'outsourceProcessIn' => [
                        'method' => '',
                        'option' => 0,
                    ],
                    'outsourceStrictPick' => '1',
                    'outsourceBaseWithTax' => 0,
                    'outsourceStrictInStock' => '1',
                ],
                '物流'=>[
                    'sourceOrder' => [
                        'saleSendOrder',
                    ],
                    'autoOutStock' => '1',
                ],
                '库存'=>[
                    'autoBatch' => [
                        'method' => '现存量',
                        'option' => '1',
                    ],
                    'estimateIn' => [
                        'purchaseWaitIn',
                        'allocationWaitIn',
                        'machiningWaitIn',
                    ],
                    'estimateOut' => [
                        'sendWaitIn',
                        'pickWaitOut',
                        'ingOrderWaitOut',
                    ],
                    'zeroOutCtrl' => '1',
                    'mrpWarehouse' => [
                        'aa78f3ab09c6c945',
                        'a7d860712d4a8038',
                        'a37e413d8b922156',
                        'aaf4d39671378ad6',
                        'a4448d3a97f30db5',
                        'a53bd5b022c8ca4e',
                        'a5bb1582d845ef82',
                        'a6830d975e7d1083',
                        'a6b0da86d5223347',
                        'a9ad7cbb06387d78',
                        'aae7a8911c82f4e0',
                        'ab6435327d036409',
                    ],
                    'outAllowZero' => '1',
                    'inventoryCtrl' => [
                        'val' => [
                            'saleSendOrder',
                            'inventoryOrder',
                        ],
                        'option' => '1',
                    ],
                    'noCheckManage' => 0,
                    'warehousePosition' => [
                        'auto' => '1',
                        'method' => 'auto',
                        'option' => '1',
                    ],
                    'inventoryStockCtrl' => '1',
                    'inventoryStockWarn' => '1',
                ],
                '核算'=>[
                    'costRate' => [
                        'rate' => '10',
                        'option' => '1',
                    ],
                    'refundPrice' => '结存成本',
                    'inStockPrice' => '上次出库成本',
                    'outStockPrice' => '参考成本',
                    'costValueMethod' => '手工录入',
                    'machiningInOrderShowDetail' => '1',
                ],
                '生产'=>[
                    'piecePrice' => [
                        'method' => '',
                        'option' => 0,
                    ],
                    'reverseCheck' => 0,
                    'processSecUnit' => [
                        'method' => '',
                        'option' => 0,
                    ],
                    'autoNewSendOrder' => '1',
                    'machiningAllowAdd' => 0,
                    'machiningOrderBom' => [
                        'method' => '',
                        'option' => 0,
                    ],
                    'beyondPurchasePlan' => 0,
                    'mobileProcessSplit' => 0,
                    'allowMoreProcessNum' => '1',
                    'beyondMachiningPlan' => 0,
                    'beyondOutsourcePlan' => 0,
                    'mobileProcessChoose' => [
                        'method' => 'zero',
                        'option' => 0,
                    ],
                    'processReportByFlow' => [
                        'method' => '',
                        'option' => 0,
                    ],
                    'productWithOutCheck' => [
                        'way' => 'endNum',
                        'method' => '提交',
                        'option' => '1',
                    ],
                    'machiningOrderStrict' => '1',
                    'machiningOrderStrictIn' => 0,
                    'mobileProcessDefaultNum' => [
                        'num' => 0,
                        'method' => 'zero',
                        'option' => 0,
                    ],
                    'machiningOrderPickStrict' => [
                        'method' => '',
                        'option' => 0,
                    ],
                    'materialControlAfterSend' => [
                        'method' => '',
                        'option' => 0,
                    ],
                    'machiningOrderProcessStrict' => [
                        'method' => '',
                        'option' => 0,
                    ],
                ],
                '质量'=>[
                    'checkOrderBad' => [
                        'val' => 'checkNum',
                        'option' => '1',
                    ],
                    'checkOrderDefault' => [
                        'val' => '单据数量',
                        'option' => '1',
                    ],
                    'productNumControll' => [
                        'way' => 'finalProcess',
                        'method' => '提交',
                        'option' => '1',
                    ],
                    'selfMadeOrderCheck' => [
                        'val' => [
                        ],
                        'option' => 0,
                    ],
                    'purchaseAutoInStock' => 0,
                    'maintainQualityOrder' => [
                        'val' => [
                        ],
                        'option' => 0,
                    ],
                    'diffPassAndFailedBatch' => [
                        'val' => '',
                        'option' => 0,
                    ],
                ],
                '往来账/出纳'=>[
                    'endToBook' => '1',
                    'feeNeedApply' => 0,
                    'outsourceForPay' => 0,
                    'purchaseNeedPay' => 0,
                    'cashAndBankAudit' => '1',
                    'otherPayNeedApply' => 0,
                    'purchaseOrderForPay' => 0,
                ],
                '总账'=>[
                    'dayBook' => 0,
                    'deficit' => 0,
                    'cashFlow' => 0,
                    'lossRate' => 2,
                    'assetCode' => 0,
                    'sameAudit' => '1',
                    'codeLength' => [
                        '2',
                        '2',
                        '2',
                    ],
                    'cashierSign' => '1',
                    'depreciation' => '1',
                    'invoicePrice' => '6',
                    'numPrecision' => [
                        'num' => '2',
                        'numLostZero' => 0,
                    ],
                    'afterAuditMark' => 0,
                    'conversionRate' => 2,
                    'pricePrecision' => [
                        'num' => '2',
                        'priceLostZero' => 0,
                    ],
                    'depreciationrate' => '2',
                ],
            ];
            $publicSettings = $setting['公共'];
            foreach ($setting as $key=>$val) {
                static::insert(array(
                    'table' => 'option_setting',
                    'field' => [
                        'id' => self::getId(),
                        'coid' => self::$coid,
                        'type' => $key,
                        'setting' => json_encode($val,320),
                    ],
                ));
            }
        }
        return $publicSettings;
    }

	/**
	 * 查找当前使用的coid
	 *
	 * @return mixed
	 */
	public static function findCoid(): mixed
	{
		$company = query('company', "isDel=0");
		if (empty($company['coid'])) {
			//默认账套
			static::insert(array(
				'table' => 'company',
				'field' => [
					'coid'      => self::getId(),
					'name'      => '默认账套',
					'startDate' => date('Y-m'),
					'rule'      => 'smallEnterpriseRule',
					'taxType'   => '小规模纳税人',
					'isAudit'   => 0,
					'isDel'     => 0,
					'stid'      => 'Ore126054470Vd',
				],
			));
		}

		$record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
		if (empty($record['id'])) {
			$company = query('company', "isDel = 0");
			self::updateCoidRecord($company['coid']);
			return $company['coid'];
		}
		return $record['value'];
	}

	/**
	 * 记录当前使用的账套
	 */
	public static function updateCoidRecord($coid): bool
	{
		if (empty($coid)) {
			return false;
		}
		$record = query('user_setting', "stid = '" . self::$stid . "' and type = '当前使用账套'");
		if (empty($record['id'])) {
			$warn = static::insert(array(
				'table' => 'user_setting',
				'field' => [
					'type'  => '当前使用账套',
					'value' => $coid,
					'stid'  => self::$stid,
				],
			));
		} else {
			$warn = static::update(array(
				'table' => 'user_setting',
				'field' => [
					'value' => $coid,
				],
				'where' => "id = '$record[id]'",
			));
		}
		if (in_array($warn, ['新增成功', '更新成功'])) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取用户权限
	 *
	 * @return array
	 */
	public static function getUserPower(): array
	{
		$array     = [];
		$roleArray = (array)json_decode(self::$user['role'], true);
		if ($roleArray) {
			foreach ($roleArray as $id) {
				$role  = query('role', " id = '$id' ");
				$temp  = isset($role['power']) ? (array)json_decode($role['power'], true) : [];
				$array = array_merge($array, $temp);
			}
		}
		return $array;
	}

	/**
	 * 权限函数
	 *
	 * @param string $page
	 * @param string $power
	 * @return bool
	 */
	public function power(string $page, string $power): bool
	{
		return in_array($power, isset($this->controlPower[$page]) ? (array)$this->controlPower[$page] : []);
	}

	/**
	 * 查看自己
	 *
	 * @param string $page
	 * @param string $field
	 * @return string
	 */
	public function seeSelf(string $page, string $field = 'stid'): string
	{
		$where = '';
		if (!$this->power($page, 'seeAll')) {
			$where = " and $field = '{$this->control['stid']}' ";
		}
		return $where;
	}

	/*添加日志
    $data = array(
        "type" => "configure.php中的权限类型，如job，client",
        "text" => "日志说明",
        "stid" => "编辑人",//非必填
    );
    */
	public function logText($data)
	{
		$finger = 0;
		//检查权限
		foreach ($this->powerAll as $twoArray) {
			foreach ($twoArray as $threeArray) {
				unset($threeArray['attribute']);
				if (array_key_exists($data['type'], $threeArray)) {
					$finger = 2;
				}
			}
		}

		//判断
		if ($finger != 2) {
			test("【" . $data['text'] . "】日志插入失败，原因：未找到权限类型");
		} elseif (empty($data['text'])) {
			test("【" . $data['type'] . "】日志插入失败，原因：日志说明为空");
		} else {
            $data['coid'] = self::$coid;
			if (empty($data['stid'])) {
				$data['stid'] = $this->control['stid'];
			}
			$data['time'] = date("Y-m-d H:i:s");
			return insert(["table" => "log", "field" => $data]);
		}
		return false;
	}

	/**
	 * 登录
	 */
	public function login()
	{
		//生成表单
		$tr    = [
            "<i class='company-login'></i>" => text(
                ["name" => "company", "title" => "企业名称", 'blur' => 'validate', "other" => 'required ']
            ),
			"<i class='user-login'></i>" => text(
				["name" => "userName", "title" => "用户名", 'blur' => 'validate', "other" => 'required pattern="\S+.*" ']
			),
			"<i class='pwd-login'></i>"  => password(
				["name" => "password", "title" => "密码", 'blur' => 'validate', "other" => 'required pattern="\S+.*" ']
			),
		];
		$table = "<table>\n";
		foreach ($tr as $key => $value) {
			$table .= "<tr>\n<td>" . $key . "</td>\n<td>" . $value . "</td>\n</tr>";
		}
		$table .= "\n</table>";
		//生成页面
		$html = "
		 <img class='loginBack' src='" . img("reportBackImg") . "'>
       </div>
		<div class='loginWin'>
            <div class='login-header'>
            </div>
            <div class='login-main'>
                <img class='loginIco' src='" . root . "img/svg/adloginIco.svg'>
                <h2>报工系统</h2>
                <div id='login-main-account'>
                    <form name='loginForm'>
                        " . $table . hidden(['name' => 'did', 'id' => 'did']) . "
                    </form>
                </div>
                <div id='login-main-qr' class='hide'>
                </div>
            </div>
            <div class='login-bottom'>
                <p>
                    <button subButton='yes' type='button' class='subButton'  id='login-submit' onClick=\"subForm('loginForm',root+'library/libData.html?type=reportLogin')\">登录</button>
                </p>
            </div>
		</div>";
		$js   = "
        <script src=\"{$this->root}static/javascript/fingerprint2.min.js\"></script>
        <script>
        $(function(){
            const did = document.getElementsByName('did');
            if (window.requestIdleCallback) {
                requestIdleCallback(function() {
                    Fingerprint2.get(function(components) {
                        const values = components.map(function(component) {
                            return component.value
                        });
                        const murmur = Fingerprint2.x64hash128(values.join(''), 31);
                        console.log(murmur);
                        did[0].value = murmur;
                    });
                })
            } else {
                setTimeout(function() {
                    Fingerprint2.get(function(components) {
                        const values = components.map(function(component) {
                            return component.value
                        });
                        const murmur = Fingerprint2.x64hash128(values.join(''), 31);
                        console.log(murmur);
                        did[0].value = murmur;
                    })
                }, 500)
            }
            // 登录函数
            login();
        })
        </script>";
		return head("report") . $html . $js . warn() . "\n</body>\n</html>";
	}

	/*报工段公共头*/
    public function commonHead($title){
        $team_detail = query("team_detail"," coid = '".self::$coid."' and stid = '".self::$stid."' ");
        $team = query("team"," id = '".$team_detail['orderId']."' ");
        return "<div class='header'>
           <p class='header-left' onclick=\"animatedOperation('navigation','left','show')\"><img src='".root."img/control/bill.svg' alt=''><span>$title</span></p>
           <p".para('companyName')."</p>
           <p class='header-right'><span>{$team['name']}</span><span>{$this->control['name']}</span><img onclick=\"window.location.href=root+'pad/index.html?cla=login&fun=out'\" src='".root."img/control/loginout.svg' alt=''></p>
		</div>
        ";
    }
    /*报工段公共导航*/
    public function commonNavigation($type){
        //根据员工选择器的值和当前员工的部门，职位，员工ID求交集
        $idColloection = $this->staffCombination(true);
        $company       = idSelect([
            'name'     => 'coid',
            'id'       => 'report_coid',
            'value'    => self::$coid,
            'sqlForm'  => "company where (selector is null or (concat(',',replace(selector,';',','),',') regexp concat(',',replace('$idColloection',',',',|,'),','))>0)",
            'class'    => 'company-select',
            'sqlId'    => 'coid',
            'sqlField' => 'name',
            'null'     => true,
        ]);
        $li = "";
        foreach ($this->config as $key=>$val) {
            $class = $type==$val?'navigation-check':'';
            $li .= "<li onclick=\"window.location.href=root+'pad/index.html?cla={$key}&fun=home'\" class='$class'>$val</li>";
        }
        return "<div class='navigation' style='display: none;'>
            <p>$company</p>
            <p class='navigation-title'>功能</p>
            <ul>
                $li
            </ul>
        </div>";
    }

    /**公共筛选类***/
    public function choiceBlock($type='dispatch'){
        $data = isset($_SESSION[$type]['search'])?$_SESSION[$type]['search']:[];
        $html = "";
        foreach ($data as $array){
            $html .= "<p class='option-title'>{$array['text']}</p>";
            $name = $array['type'] == 'radio'?$array['name']:$array['name'].'[]';
            $span = "";
            if (array_values($array['value']) === $array['value']) {
                foreach ((array)$array['value'] as $item) {
                    $checked = $item['checked'] ? "checked" : "";
                    $class = $item['checked'] ? "option-item-checked" : "";
                    $span .= "<span onclick=\"clickSelect(this,'{$array['type']}')\" class='$class'>{$item['name']}<input name='" . $name . "' type='".$array['type']."' style='display:none;' value='" . $item['name'] . "' " . $checked . "></span>";
                }
            }else{
                foreach ((array)$array['value'] as $key => $item) {
                    $checked = $item['checked'] ? "checked" : "";
                    $class = $item['checked'] ? "option-item-checked" : "";
                    $span .= "<span onclick=\"clickSelect(this,'{$array['type']}')\" class='$class'>{$item['name']}<input name='" . $name . "' type='".$array['type']."' style='display:none;' value='" . $key . "' " . $checked . "></span>";
                }
            }
            $html .= "<p class='option-item'>$span</p>";
        }
        return "<div class='choice-block' style='display: none;'>
            <form name='searchForm' style='position: relative;height: 100%;'>
                <div class='select-area'>
                    <p class='option-text'>筛选</p>
                    $html
                </div>
                <div class='option-but-block'>
                    <p><span class='reset-but' onclick='reset()'>重置</span></p>
                    <p><span class='cancel-but' onclick=\"animatedOperation('choice-block','right','hide')\">取消</span><span class='sure-but' onclick=\"searchFormRender('$type')\">确定</span></p>
                </div>
            </form>
        </div>";
    }


    public function getTimePeriod(string $time, string $type = 'date', string $field = 'time'){
        $today = date("Y-m-d");
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $tomorrow = date("Y-m-d",strtotime("+1 day"));
        switch ($time)
        {
            case "今天":
                $quantum = $today.' ~ '.$today;
                break;
            case "昨天":
                $quantum = $yesterday.' ~ '.$yesterday;
                break;
            case "近三天":
                $quantum = $yesterday.' ~ '.$tomorrow;
                break;
            case "本周":
                $thisweek_start = date("Y-m-d",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
                $thisweek_end = date("Y-m-d",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
                $quantum = $thisweek_start.' ~ '.$thisweek_end;
                break;
            case "本月":
                $thismonth_start = date("Y-m-d",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $thismonth_end = date("Y-m-d",mktime(23,59,59,date("m"),date("t"),date("Y")));
                $quantum = $thismonth_start.' ~ '.$thismonth_end;
                break;
            default:
                $quantum = '';
        }
        return $quantum?self::timeComparison($quantum,$type,$field):'';
    }

    /*分页
    $data = array(
        "table" => "要查询的表名称",
        "where" => "查询条件",
        "order" => "排序方式",
        "pageNum" => "每页显示记录条数",
        "buttonNum" => "要显示的分页按钮数量",
    );
    */
    public function pageSmall(array $data)
    {
        $fun = $data['fun']?:'getTeam';
        $data['field'] = $data['field'] ?? '*';
        $data['order'] = $data['order'] ?? '';
        $data['union'] = $data['union'] ?? '';
        //修正每页显示的条数
        if (empty($data['pageNum']) or preg_match(checkInteger, $data['pageNum']) == 0) {
            $data['pageNum'] = (int)para('numberOfPageItems');
        }
        //修正分页按钮数量
        if (empty($data['buttonNum']) or preg_match(checkInteger, $data['buttonNum']) == 0) {
            $data['buttonNum'] = 7;
        }
        if (str_contains(strtolower(trim($data['table'] . $data['where'] . $data['order'])), 'group')) {
            //group by 查询方式
            $sql    = $this->getSql(
                array(
                    "table" => $data['table'],
                    "field" => $data['field'],
                    "where" => $data['where'] . ($data['order'] ? (" order by " . $data['order']) : ''),
                )
            );
            $sqlNum = $this->totalGroupNum($sql);
        } elseif ($data['union']) {
            //联表
            $sqlNum = static::total(array('sql' => "select ifnull(sum(a.num),0) as total from ({$data['union']}) as a")); //总条数
        } else {
            $sqlNum = static::total(array('table' => $data['table'], 'where' => $data['where'])); //总条数

        }
        $pageAll = is_numeric($sqlNum) ? ceil($sqlNum / $data['pageNum']) : exit($sqlNum);//总页数
        //修正当前页
        if ($this->get('page') > 1 and $this->get('page') <= $pageAll) {
            $pageNow = $this->get('page');
        } else {
            $pageNow = 1;
        }
        //判断要显示的第一个页码
        $pageCenter = ceil($data['buttonNum'] / 2); //底部分页按钮的居中页
        if ($pageNow <= $pageCenter) {//如果当前页小于等于居中页
            $pageFirst = 1;
        } elseif (($pageAll - $pageNow) <= $pageCenter) {  //如果当前页后面的页数小于等于居中页
            $pageFirst = $pageAll - $data['buttonNum'] + 1;//则把最后的几个页码显示出来
        } else {
            $pageFirst = $pageNow - $pageCenter;//如果当前页两边都有充足的页面，则居中显示
        }
        //拼接页码按钮
        $pageButton = "";
        for ($x = 0; $x < $data['buttonNum']; $x++) {
            $n = $pageFirst + $x;
            if ($n > 0 and $n <= $pageAll) {//$n可能小于零或大于总页数
                if ($n == $pageNow) {
                    $c = " class='pageNow' ";
                } else {
                    $c = "";
                }
                $pageButton .= "<li " . $c . " onclick=\"searchForm('" . $this->get('cla') . "','" . $fun . "'," . $n . ")\">" . $n . "</li>\n";
            }
        }
        //分页下拉菜单
        $option = "";
        if ($pageAll > 0) {
            for ($x = 1; $x <= $pageAll; $x++) {
                if ($pageNow == $x) {
                    $selected = " selected='selected' ";
                } else {
                    $selected = "";
                }
                $option .= "<option value='" . $x . "' " . $selected . ">第" . $x . "页</option>";
            }
        } else {
            $option .= "<option value='1'>第1页</option>";
        }
        //分页html
        $pageLast         = $pageNow <= 1 ? 1 : $pageNow - 1; //上一页
        $pageNext         = $pageNow >= $pageAll ? $pageAll : $pageNow + 1; //下一页
        $result['button'] = "
		<div class='pageButton'>
			<ul>
				<li onclick=\"searchTeam('" . $this->get('cla') . "','" . $fun . "'," . $pageLast . ")\">上一页</li>
				" . $pageButton . "
				<li onclick=\"searchTeam('" . $this->get('cla') . "','" . $fun . "'," . $pageNext . ")\">下一页</li>
			</ul>
		</div>
		";
        //数据库查询结果
        $sqlFirst = ($pageNow - 1) * $data['pageNum'];                                                     //当前页面开始位置
        $sqlTable = find(
            array(
                "table" => $data['table'],
                "field" => $data['field'],
                "where" => $data['where'] . ($data['order'] ? (" order by " . $data['order']) : '') . " limit " . $sqlFirst . "," . $data['pageNum'],
            )
        );
        if (is_array($sqlTable)) {
            $result['sql']     = $sqlTable['sql'];
            $result['array']   = $sqlTable['array'];
            $result['fullSql'] = $this->interceptString($result['sql'], 'limit');
        } else {
            $result['sql']     = $sqlTable;
            $result['fullSql'] = $this->interceptString($result['sql'], 'limit');
            $result['array']   = [];
        }
        //提示
        $result['hint'] = "
		<span class='pageHint'>
			共找到" . $sqlNum . "条数据&nbsp;&nbsp;
			第" . $pageNow . "页/
			共" . $pageAll . "页
		</span>
		";
        //返回
        return $result;
    }

    public function jsReport(){
        $num = self::$publicSettings['numPrecision']['num'];
        return <<<eof
<script>
        function clickSelect(obj,type){
            let parent = $(obj).parent()
            if(type === 'radio'){
                parent.find('span').removeClass('option-item-checked')
                parent.find('input').prop('checked',false)
                $(obj).addClass('option-item-checked')
                $(obj).find('input').prop('checked',true)
            }else if(type === 'checkbox'){
                if($(obj).find('input').is(':checked')) {
                    $(obj).removeClass('option-item-checked')
                    $(obj).find('input').prop('checked',true)
                }else{
                    $(obj).addClass('option-item-checked')
                    $(obj).find('input').prop('checked',true)
                }
            }
        }
        function reset(){
            $("[name='searchForm']").find('span').removeClass('option-item-checked')
            $("[name='searchForm']").find('input').removeAttr('checked')
        }
        function searchFormRender(type) {
            let orderNo = $("[name='orderNo']").val()
            animatedOperation('choice-block','right','hide')
            let url = root+'pad/index.html?cla='+type+'&fun=conditions'
            //异步提交数据
            $.post(url, $("[name=searchForm]").serialize()+'&orderNo='+orderNo, function (data) {
                if(data.warn === 2){
                    window.location.reload();
                }
            }, "json");
        }
        function animatedOperation(node,direction,operate){
            if(operate === 'show'){
                if(direction === 'left'){
                    $('.'+node).finish().removeClass('fadeOutLeft').show().addClass('animated fadeInLeft');
                }else{
                    $('.'+node).finish().removeClass('fadeOutRight').show().addClass('animated fadeInRight');
                }
            }else{
                if(direction === 'left'){
                    $('.'+node).finish().removeClass('fadeInLeft').addClass('fadeOutLeft').delay(1000).hide('');
                }else{
                    $('.'+node).finish().removeClass('fadeInRight').addClass('fadeOutRight').delay(1000).hide('');
                }
            }
            
        }
        //点击非下拉区域隐藏
        $(document, window.parent.document).bind('click', function (e) {
            let target = $('.choice-block', window.parent.document)
            let header = $('.search-right', window.parent.document)
            if (!target.is(e.target) && target.has(e.target).length === 0 && !header.is(e.target) && header.has(e.target).length === 0) {
                animatedOperation('choice-block','right','hide')
            }
            target = $('.navigation', window.parent.document);
            header = $('.header-left', window.parent.document);
            if (!target.is(e.target) && target.has(e.target).length === 0 && !header.is(e.target) && header.has(e.target).length === 0) {
                animatedOperation('navigation','left','hide')
            }
        });
        
        //数字键盘
        $('.calculator').on('click', '.key-item', function () {
            var num = $(this).data('num')
            var name = $(this).data('name')
            var getNum = $("[name='"+name+"']")
            var currentNum = String(getNum.val())
            switch (String(num)) {
                //小数点
                case 'spot':
                    if(currentNum.indexOf(".") <= 0 && currentNum !== '' && currentNum !== undefined) {
                        currentNum += '.';
                        getNum.val(currentNum);
                    }
                    break;
                //删除键
                case 'delete':
                    var deleteNum = currentNum.slice(0, -1)
                    getNum.val(deleteNum);
                    break;
                default:
                    currentNum += num;
                    currentNum = currentNum.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
                    currentNum = currentNum.replace(/^\./g,""); //验证第一个字符是数字
                    currentNum = currentNum.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
                    currentNum = currentNum.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
                    currentNum = currentNum.replace(/^(\-)*(\d+)\.(\d{{$num}}).*$/,'$1$2.$3'); //只能输入两个小数
                    getNum.val(currentNum);
                    break;
            }
        })
        //工序
        $('.process').on('click', '.process-item', function () {
           var name = $(this).data('name')
           var id = $(this).data('id')
           $("#processName").text(name)
           $("[name='processId']").val(id)
           $(".process-item").removeClass('choice-font')
           $(this).addClass('choice-font')
        })
        //班组
        $('#getTeamHtml').on('click', '.team-item', function () {
           var name = $(this).data('name')
           var id = $(this).data('id')
           $("#teamName").text(name)
           $("[name='teamId']").val(id)
           $(".team-item").removeClass('choice-font')
           $(this).addClass('choice-font')
        })
        //班组查询
        function searchTeam(cla, fun, page, formData = false) {
            let params = (formData === true) ? $("[name=" + fun + "Form]").serialize() : formData
            $.post(root + "pad/index.html?cla=" + cla + "&fun=" + fun + "&page=" + page, params, function (data) {
                if (data.warn) {
                    warn(data.warn);
                } else {
                    $("#" + fun + "Html").html(data.html);
                }
            }, "json");
        }
        $("#report_coid").on('change', function () {
            let coid = $(this).val();
            if (coid.length <= 0) {
                msg('请选择账套', 'error');
            } else {
                let con = setTimeout(function () {
                    $("#loading", window.top.document).hide();
                }, lib_configurg.loading_time_out);
                $("#loading", window.top.document).show();
                $.post(root + "control/adIndex.html?cla=homepage&fun=updateCoid", {
                    'coid': coid
                }, function (data) {
                    if (data.warn === 2) {
                        href('pad/index.html');
                    } else {
                        msg(data.warn, 'error');
                    }
                    $("#loading", window.top.document).hide();
                    clearTimeout(con);
                }, "json")
            }
        })
</script>
eof;
    }



	/*展示型table拼接-按钮，不同类型的按钮对应不同的参数
    $data = array(
        array(
            "name" => "按钮名称",
            "type" => "弹出层",//按钮类型
            "cla" => "需要调用的类名称",
            "fun" => "需要调用的函数名称",
            "post" => "向调用的函数传递的POST参数",
            'style' => '附加类'
        ),
        array(
            "name" => "按钮名称",
            "type" => "文件下载",
            "fileName" => "文件名称",
            "url" => "文件路径",
        ),
        array(
            "name" => "按钮名称",
            "type" => "顶部页卡",
            "title" => "顶部页卡标题",
            "url" => "顶部页卡路径",
        ),
        array(
            "name" => "按钮名称",
            "type" => "外部链接",
            "url" => "路径",
        ),
        array(
            "name" => "按钮名称",
            "type" => "点击事件",
            "fun" => "js函数",
        ),
    );
    */
	public function tableShowButton($data)
	{
		//初始化
		$li      = $html = "";
		$liClass = [
			"弹出层"   => "alert",
			"文件下载" => "download",
			"顶部页卡" => "toppage",
			"外部链接" => "href",
			"点击事件" => "click",
		];
		//遍历
		foreach ($data as $array) {
			$style = isset($array['type']) ? ("class='li-btn-" . $liClass[$array['type']] . (isset($array['style']) && $array['style'] ? ' ' . $array['style'] . ' ' : '') . "'") : '';
			switch ($array['type']) {
				case '弹出层':
					$post = [];
					foreach ($array['post'] as $k => $v) {
						$post[] = "'" . $k . "':'" . $v . "'";
					}
					$json = "{" . implode(",", $post) . "}";
					$li   .= "<li onclick=\"layer('" . $array['cla'] . "','" . $array['fun'] . "'," . $json . ")\" " . $style . ">" . $array['name'] . "</li>";
					break;
				case '文件下载':
					$li .= "<li " . $style . "><a href='" . $array['url'] . "' download='" . $array['fileName'] . "' target='_blank'>" . $array['name'] . "</a></li>";
					break;
				case '顶部页卡':
					$li .= "<li onclick=\"newIframe('" . $array['title'] . "','" . $array['url'] . "')\" " . $style . ">" . $array['name'] . "</li>";
					break;
				case '外部链接':
					$li .= "<li " . $style . "><a href='" . $array['url'] . "' target='_blank'>" . $array['name'] . "</a></li>";
					break;
				case '点击事件':
					$li .= "<li onclick=\"" . $array['fun'] . "\" " . $style . ">" . $array['name'] . "</li>";
					break;
				default:
					$li .= "no";
					break;
			}
		}
		//按钮拼接
		if (isset($li) && $li) {
			$html = "<ul class='liButton'>" . $li . "</ul>" . clear;
		}
		//返回
		return $html;
	}

	/*展示型table拼接*/
	public function tableShow($data)
	{
		//初始化
		$html = "";
		$max  = 0;
		//获取表格最大列数
		foreach ($data as $oneKey => $ulArray) {
			if ($oneKey !== "button") {
				foreach ($ulArray as $twoKey => $liArray) {
					$num = count($liArray);
					if ($num > $max and $twoKey !== "button") {
						$max = $num;
					}
				}
			}
		}
		//数据分析
		foreach ($data as $oneKey => $ulArray) {
			if ($oneKey === "button") {
				$html .= $this->tableShowButton($ulArray);
			} else {
				//拼接表格
				$button = $ul = "";
				foreach ($ulArray as $twoKey => $liArray) {
					if ($twoKey === "button") {
						$button = $this->tableShowButton($liArray);
					} else {
						//初始化参数
						$n     = 0;
						$liNum = count($liArray);
						$li    = "";
						//遍历数组
						foreach ((array)$liArray as $key => $value) {
							//计数
							$n++;
							//内容
							$value = kong($value);
							if (is_int($key)) {
								$content = $value;
							} else {
								$content = $key . "：" . $value;
							}
							//如果单元格不足，则补全
							if ($liNum < $max and $liNum == $n) {
								$m     = $max - $liNum + 1;
								$style = " style='flex:" . $m . "' ";
							} else {
								$style = "";
							}
							//拼接本单元格
							$li .= "<li " . $style . ">" . $content . "</li>";
						}
						//拼接本行
						$ul .= "<ul class='show'>" . $li . "</ul>";
					}
				}
				//没有键名的数组，置为空
				if (is_int($oneKey)) {
					$oneKey = '';
				}
				if (count($ulArray) > 0) { //数组中有值才显示
					//拼接本表格
					$html .= "
                            <div class='tableShow'>
                                <p>" . $oneKey . "</p>
                                " . $button . $ul . "
                            </div>
                            ";
				}
			}
		}
		//返回
		return $html;
	}

	/*文件创建与编辑函数
    $data = array(
        "url" => "文件路径",
        "text" => "文件内容",
    );
    */
	public function fileEdit($data)
	{
		if (file_exists($data['url'])) {
			file_put_contents($data['url'], $data['text']);
		} else {
			$array = explode("/", $data['url']);
			$url   = "";
			foreach ($array as $name) {
				if (!empty($name)) {
					$url .= "/" . $name;
					if (!file_exists($url)) {//如果此路径不存在
						if ($url == $data['url'] and strstr($name, ".")) {//如果已经拼接到完整路径，且检查到最末端带文件名后缀，则说明需要创建文件，而非文件夹
							$file = fopen($url, "w");                     //创建文件
							fwrite($file, $data['text']);                 //写入文件内容
						} else {
							mkdir($url);//则创建文件目录
						}
					}
				}
			}
		}
	}

	/*列表页控件
    $data = array(
        //列表多选框
        "box" => array(
            "name" => "多选框名称",
            "value" => "多选框值",
        ),
        //按钮
        "见$para变量" => array(
            "title" => "标题",
            "click" => "点击事件",
        ),
        //文件下载
        "download" => array(
            "type" => "文件类型，如doc,xls",
            "name" => "文件名称",
            "href" => "文件跟目录路径",
        ),
        //文件预览
        "preview" => array(
            "format" => "文件格式，如doc,xls",
            "name" => "文件名称",
            "href" => "文件跟目录路径",
        ),
        //图片预览
        "img" => array(
            "title" => "标题",
            "href" => "根目录路径",
        ),
    );
    */
	public function dominate($data)
	{
		//参数准备
		$html = "";
		$para = array(
			"detail"       => "详情",
			"edit"         => "编辑",
			"auditing"     => "审核",
			"rebut"        => "驳回",
			"upload"       => "上传",
			"share"        => "分享",
			"affair"       => "事务",
			"agent"        => "代理",
			"client"       => "客户",
			"order"        => "订单",
			"project"      => "项目",
			"allot"        => "任务",
			"invoice"      => "发票填开",
			"use"          => "资产领用",
			"useRecord"    => "领用记录",
			"cut"          => "资产核减",
			"cutRecord"    => "核减记录",
			"revert"       => "资产归还",
			"revertRecord" => "归还记录",
			"copy"         => "复制",
			"code"         => "代码",
			"signYellow"   => "已标记",
			"signGray"     => "未标记",
			"download"     => "下载",
			"preview"      => "文档预览",
			"img"          => "图片预览",
			'browse'       => '预览',
			"follow"       => "跟进记录",
			"obtain"       => '获取',
			'print'        => '打印',
			'scrap'        => '报废',
			'rework'       => '返工',
			'receive'      => '接收',
			'refund'       => '退货',
			'backCar'      => '还车',
			'add'          => '增加',
			'report'       => '报工',
			'track'        => '单据追踪',
		);
		//循环
		foreach ($data as $name => $array) {
			//标题
			$title = (empty($array['title'])) ? ($para[$name] ?? null) : $array['title'];

			if (empty($array)) {
				continue;
			}
			//生成HTML
			if ($name == "box") {
				$html .= "\n<label class='listCheckbox'><input name='" . $array['name'] . "[]' type='checkbox' value='" . $array['value'] . "'/><span></span></label>";
			} elseif ($name == "download") {
				if (!empty($array['href'])) {
					$html .= "\n<a target='_blank' href='" . root . $array['href'] . "' download='" . $array['name'] . "' title='" . $title . "'><img src='" . root . "img/control/download.svg' class='listIco'></a>";
				}

			} elseif ($name == "preview") {
				if (!empty($array['href'])) {
					$url  = fileUploadClass::wpsView($array);
					$html .= "\n<a target='_blank' href='" . $url . "' title='" . $title . "'><img src='" . root . "img/control/preview.svg' class='listIco'></a>";
				}

			} elseif ($name == "img") {
				if (!empty($array['href'])) {
					$html .= "\n<a target='_blank' href='" . root . $array['href'] . "?time=" . time() . "'><img src='" . root . "img/control/img.svg' title='" . $title . "' class='listIco'></a>";
				}
			} elseif (array_key_exists($name, $para)) {
				$html .= "\n<img onclick=\"" . $array['click'] . "\" title='" . $title . "' src='" . root . "img/control/" . $name . ".svg' class='listIco'>";
			}
		}
		//返回
		return $html;
	}

	/*wps文件预览
    $data = array(
        "format" => "文件格式，如doc,xls",
        "name" => "文件名称",
        "href" => "文件跟目录路径",
    );
    */
	public static function wps($data)
	{
		//参数准备
		$wpsAppKey = para("wpsAppKey");
		$para      = array(
			"_w_appid"  => para("wpsAppId"),
			"_w_userid" => self::$stid,
			"_w_fileId" => suiji(),
			"_w_name"   => getVal($data, 'name'),
			"_w_href"   => getVal($data, 'href'),
		);
		//判断文件类型
		$formatArray = array(
			"w" => array("doc", "docx"),
			"s" => array("xls", "xlsx"),
			"p" => array("ppt", "pptx"),
			"f" => array("pdf"),
		);
		$format      = '';
		foreach ($formatArray as $key => $value) {
			if (in_array($data['format'], $value)) {
				$format = $key;
			}
		}
		//按照键名对数组升序排序
		ksort($para);
		//生成签名字符串
		$get = $str = "";
		foreach ($para as $key => $value) {
			$str .= $key . "=" . $value;
			$get .= $key . "=" . $value . "&";
		}
		$str .= "_w_secretkey=" . $wpsAppKey;
		//签名
		$sign = hash_hmac('sha1', $str, $wpsAppKey, true);
		$sign = base64_encode($sign);
		$sign = urlencode($sign);
		$get  .= "_w_signature=" . $sign;
		//生成URL
		return "https://wwo.wps.cn/office/" . $format . "/" . $para['_w_fileId'] . "?" . $get;
	}


	/*审批记录
    $typeId:审批对象ID号
    */
	public function auditingFollow($typeId)
	{
		$sql = find(array("table" => "auditing_follow", "where" => " typeId = '" . $typeId . "' order by time desc"));
		if ($sql['num'] == 0) {
			$html = "<div class='record'>无审批记录</div>";
		} else {
			$html = "";
			foreach ($sql['array'] as $array) {
				$text = preg_replace(array("/\n/"), array("<br>"), $array['text']);
				$html .= "<div class='record'>" . $text . "\n<span class='gray'>" . $array['time'] . "</div>";
			}
		}
		return $html;
	}

	/*带密码的批量删除提示层*/
	public function pasWarn()
	{
		//提示信息
		$paraId = $this->post('cla') . ucwords($this->post('fun'));
		//提交按钮
		$url    = root . "control/adIndex.html?cla=" . $this->post('cla') . "&fun=" . $this->post('fun');
		$button = "<input onclick=\"subForm('pasWarnForm," . $this->post(
				'formName'
			) . "','" . $url . "')\" type='button' class='button' value='确认提交'>";
		//表单
		$html = $this->layerEdit(array(
			"table"  => array(
				array(
					"提示信息：" => para($paraId),
				),
				array(
					must . "登录密码：" => password(array("name" => "password")),
				),
			),
			"button" => $button,
		));
		//返回
		return $this->layer(array("title" => "温馨提示", "height" => 240, "width" => 600, "zindex" => 98, "html" => $html));
	}

	/*图片显示与编辑
    *$data = array(
        array(
            "title" => "标题",
            "url" => "图像服务器相对路径",
            "cla" => "提交后处理的类名称",
            "fun" => "提交后处理的函数名称",
            "id" => "需要添加或更新图片的记录的主键",
        ),
        ...
    )
    */
	public function photo($data)
	{
		$li = "";
		foreach ($data as $num => $array) {
			//编辑表单
			if (in_array("", [getVal($array, 'fun'), getVal($array, 'cla'), getVal($array, 'id')])) {
				$click = $form = "";
			} else {
				$click = "<img src='" . root . "img/images/clickEdit.png' onclick='document." . $array['fun'] . "Form.file.click();' class='clickIco'>";
				$form  = "
				<form name='" . $array['fun'] . "Form' action='" . root . "control/adIndex.html?cla=" . $array['cla'] . "&fun=" . $array['fun'] . "' method='post' enctype='multipart/form-data' class='hide'>
					<input name='file' type='file' onchange='document." . $array['fun'] . "Form.submit();'>
					<input name='id' type='hidden' value='" . $array['id'] . "'>
				</form>
				";
			}
			//点击显示大图功能
			if (empty($array['url'])) {
				$img = "<img class='smallImg imgHover' src='" . root . "img/images/emptyImg.jpg'>";
			} else {
				if (strstr($array['url'], "http") !== false) {
					$r = "";
				} else {
					$r = root;
				}
				$img = "<a target='_blank' href='" . $r . $array['url'] . "' title='点击查看大图'><img class='smallImg imgHover' src='" . $r . $array['url'] . "'></a>";
			}
			//打印本图像框
			$li .= "
			<li>
				" . $click . "
				<p>" . $array['title'] . "</p>
				<div>" . $img . "</div>
				" . $form . "
			</li>
			";
		}
		$html = "
		<div class='imgSingle'>
			<ul>" . $li . "</ul>
			<div class='clear'></div>
		</div>
		";
		return $html;
	}

	/*查询某员工的权限
    $data = array(
        "stid" => "需要查询权限的员工ID",
        "page" => "页面名称",
        "power" => "权限代码",
    );
    */
	public function staffPower($data)
	{
		$staff = query("staff", " stid = '$data[stid]' ");
		$job   = query("job", " id = '$staff[jobId]' ");
		$role  = query("role", " id = '$job[roleId]' ");
		$power = json_decode($role['power'], true);
		if (in_array($data['power'], (array)$power[$data['page']])) {
			return true;
		} else {
			return false;
		}
	}

	/*代理商详情页权限*/
	public function agentPower($agid)
	{
		//数据库查询
		$agent = query("agent", "agid = '$agid'");
		//判断
		if (empty($agid)) {
			$json['warn'] = "代理商ID号为空";
		} elseif (empty($agent['agid'])) {
			$json['warn'] = "未找到此代理商";
		} elseif ($agent['stid'] == $this->control['stid'] and !$this->power("agent", "see")) {
			$json['warn'] = "你没有查看代理商的权限";
		} elseif ($agent['stid'] != $this->control['stid'] and !$this->power("agent", "seeAll")) {
			$json['warn'] = "你没有查看全部代理商的权限";
		} else {
			$json = $agent;
		}
		//返回
		return $json;
	}

	/*数据库排序
    $data = array(
        "search" => "查询关键词",
        "default" => "默认排序关键词",
        "array" => array(//排序字典
            "排序字段名称" => array(
                "asc" => "本字段升序排序关键词",
                "desc" => "本字段降序排序关键词",
                "site" => "本字段在表格中列的位置",
            ),
        ),
    );
    */
	public function orderBy($data)
	{
		//有查询条件
		if (!empty($data['search'])) {
			$para = $this->orderByEach(array("search" => $data['search'], "array" => $data['array']));
		}
		//如未找到，则查询默认
		if (empty($para['orderBy'])) {
			$para = $this->orderByEach(array("search" => $data['default'], "array" => $data['array']));
		}
		//返回
		return $para;
	}

	/*数据库排序-循环数组
    $data = array(
        "search" => "查询关键词",
        "array" => "排序字典",
    );
    */
	public function orderByEach($data)
	{
		//参数准备
		$para = array(
			"field"   => "",//sql查询自定义字段
			"orderBy" => "",//sql查询排序代码
			"site"    => "",//排序标记列的位置
			"style"   => "",//排序标记样式
		);
		//遍历排序字典
		foreach ($data['array'] as $name => $array) {
			foreach ($array as $key => $value) {
				if ($data['search'] == $value) {
					$para['orderBy'] = $name . " " . $key;
					$para['field']   = $array['field'] ?? null;
					$para['site']    = $array['site'] ?? null;
					//排序标签
					if ($key == "desc") {
						$para['style'] = orderByDescStyle;
					} elseif ($key == "asc") {
						$para['style'] = orderByAscStyle;
					}
				}
			}
		}
		//返回
		return $para;
	}

	/*列表页table拼接
    $data = array(
        "tr" => "字段数据",
        "text" => "按字段顺序添加td的附加说明或属性",
        "thead" => "为false表示不加tbody和thead标签",
        "table" => "为false表示不加table标签",
        "end" => "为true表示不展示空数据时的占位行，即‘一条记录也没有’行",
        "button" => "为true时，且end为true时，显示底部新增按钮",
        "method" => "新增按钮附带的方法名称",
        "orderBySign" => array(
            "site" => "排序位置",
            "style" => "排序样式",
        ),
    );
    */
	public function tableMany($data): string
	{
		$first = $end = '';
		//检查最后一组是不是全是空的
		foreach ($data['tr'] as $key) {
			$firstValue = $key[0];
			if (!empty($firstValue)) {
				$first = "yes";
			}
			$endValue = end($key);
			if (!empty($endValue)) {
				$end = "yes";
			}
		}
		//组合table
		$row = "";
		$x   = 0;
		foreach ($data['tr'] as $key) {
			$td = "";
			if ($first != "yes") {
				array_shift($key);
			}
			if ($end != "yes") {
				array_pop($key);
			}
			$y = 0;

			foreach ($key as $value) {
				//如果是表头，则查询是否附带有排序标签
				$orderBySign = "";
				if (empty($row)) {
					if (!empty($data['orderBySign']['style']) and $data['orderBySign']['site'] == $y + 1) {
						$orderBySign = $data['orderBySign']['style'];
					}
					//如果不是表头且本单元格为空，则补全空字段
				} elseif ($value === "" or $value === null) {
					$value = "---";
				}
				//返回本单元格
				if (isset($data['text'])) {
					$td .= "<td " . ($data['text'][$x][$y] ?? null) . ">" . $value . $orderBySign . "</td>";
				} else {
					$td .= "<td>" . $value . $orderBySign . "</td>";
				}

				$y++;
			}
			if ($x == 0 && (!isset($data['thead']) || $data['thead'] !== false)) {
				//thead为false时，去掉thead和tbody
				$row .= "<thead><tr onclick=\"tableManyClick(this)\">" . $td . "</tr></thead>";
			} else {
				$row .= "<tr onclick=\"tableManyClick(this)\">" . $td . "</tr>";
			}
			$x++;
		}
		if (count($data['tr']) == 1 && (!isset($data['thead']) || $data['thead'] !== false)) {  //thead为false时，去掉thead和tbody
			$row .= "<tbody>";
			$n   = count($data['tr'][0]);
			if (!isset($data['end']) || !$data['end']) {
				$row .= "<tr><td colspan='" . $n . "' class='no-data'>一条记录都没有</td></tr>";
			}
		}
		if (isset($data['end']) && isset($data['button']) && $data['button']) {
			$n   = count($data['tr'][0]);
			$row .= "<tr><td colspan='" . $n . "' class='add-line-button' style='text-align: center;cursor: pointer;font-weight: bold' onclick=\"{$data['method']}\">+&nbsp;新增</td></tr>";
		}
		if (count($data['tr']) == 1 && (!isset($data['thead']) || $data['thead'] !== false)) {
			//thead为false时，去掉thead和tbody
			$row .= "</tbody>";
		}
		$js = <<<eof
<script>
 $(".winAuto .tableMany").on('click',"tr",function(e) {
   let radio = $(this).find("td:first").find("input[type='radio']")
   let checkbox = $(this).find("td:first").find("input[type='checkbox']")
   if (radio.length >0){
       radio.prop("checked",true)
   }else if(checkbox.length >0){
       if (checkbox.is(":checked")){
           checkbox.prop('checked',false)
       }else{
            checkbox.prop('checked',true)
       }
   }
 })
</script>
eof;
		if ((isset($data['thead']) && $data['thead'] === false) || (isset($data['table']) && $data['table'] === false)) {
			//table为false时，去掉table标签
			return $row;
		}

		return "<div class='table_many_shell'><table class='tableMany'>" . $row . "</table></div>" . $js;
	}

	/*编辑页table拼接*/
	public function tableEdit($trArray)
	{
		$tr = '';
		foreach ($trArray as $num => $tdArray) {
			$td = "";
			foreach ($tdArray as $key => $value) {
				if (count($tdArray) == 1) {
					if (is_int($key)) {
						$td .= "<td colspan='4'>" . $value . "</td>";
					} else {
						$td .= "<td>" . $key . "</td><td colspan='3'>" . $value . "</td>";
					}
				} else {
					$td .= "<td>" . $key . "</td><td>" . $value . "</td>";
				}
			}
			$tr .= "<tr>" . $td . "</tr>";
		}
		$html = "<table class='tableEdit'>" . $tr . "</table>";
		return $html;
	}

	/*弹出层列表样式
    $data = array(
        array(列
            "标题" => "内容",
            ...
        )...
    );
    */
	public function layerList($data)
	{
		//生成table
		$max = 0;
		foreach ($data as $array) {
			$num = count($array);
			if ($num > $max) {
				$max = $num;
			}
		}
		$ul = "";
		foreach ($data as $array) {
			//初始化参数
			$li    = "";
			$n     = 0;
			$liNum = count($array);
			//遍历数组
			foreach ($array as $key => $value) {
				//计数
				$n++;
				//如果单元格不足，则补全
				if ($liNum <= $max and $liNum == $n) {
					$m         = ($max - $liNum) * 2 + 1;
					$tempStyle = '';
					if (is_int($key)) {
						$m++;
						$tempStyle = ";text-align:left";
					}
					$style = " style='flex:" . $m . " {$tempStyle}' ";
				} else {
					$style = "";
				}
				if (is_int($key)) {
					//键名为整数时
					$li .= "<li " . $style . ">" . $value . "</li>";
				} else {
					//打印本单元格
					$key = (str_contains($key, ':') || str_contains(
							$key,
							'：'
						)) ? $key : ($key !== '&nbsp' ? $key . '：' : $key);
					$li  .= "<li>" . $key . "</li><li " . $style . ">" . $value . "</li>";
				}
			}
			$ul .= "<ul>" . $li . "</ul>";
		}
		//生成页面
		return "<div class='layerList'>" . $ul . "</div>";
	}

	/*弹出层编辑样式
    $data = array(
        "table" => "表单内容",
        "hidden" => "隐藏域",
        "button" => "表单控制按钮",//不填时生成标准提交按钮
        "formTwo" => "需要提交的第二个form表单名称",//非必填
    );
    */
	public function layerEdit($data)
	{
		//表单名称
		$form = $this->get('cla') . ucwords($this->get('fun')) . "Form";
		//拼接隐藏域
		$hidden = "";
		if (!empty($this->post('id'))) {
			$hidden .= hidden(["name" => "id", "value" => $this->post('id')]);//弹出层表单主索引
		}
		if (isset($data['hidden'])) {
			$hidden .= $data['hidden'];
		}
		//生成提交按钮
		if (empty($data['button'])) {
			if (empty($data['formTwo'])) {
				$subForm = $form;
			} else {
				$subForm = $form . "," . $data['formTwo'];
			}
			$url    = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=" . $this->get('fun') . "Edit";
			$button = "<input onclick=\"subForm('" . $subForm . "','" . $url . "')\" type='button' class='button' value='确认提交'>";
		} else {
			$button = $data['button'];
		}
		//生成表单
		return "
		<form name='" . $form . "' onsubmit='return false'>
			" . $this->layerList($data['table']) . "
			<div class='center'>" . $hidden . $button . "</div>
		</form>
		";
		//返回
	}

	/*选择全部/取消选择*/
	public function checkAll($formName, $checkName)
	{
		return "<label title='全选' class='listCheckbox'><input type='checkbox' form='" . $formName . "' name='" . $checkName . "' onchange='checkAll(this)' /><span></span></label>";
	}

	/*选择员工关联菜单
    $data = array(
        "show" => "显示层级：1、2、3、4",
        "class" => "样式",
        "departmentType" => "当前部门分类值",
        "department/job/staff" => array(
            "name" => "下拉菜单名称",
            "value" => "当前值",
        ),
    );
    */
	public function staffSelect($data)
	{
		$data['class']               = $data['class'] ?? null;
		$data['departmentType']      = $data['departmentType'] ?? null;
		$data['department']['value'] = $data['department']['value'] ?? '';
		//当前部门
		if (empty($data['department']['name'])) {
			$departmentName = "departmentId";
		} else {
			$departmentName = $data['department']['name'];
		}
		$departmentId = idSelect(array(
			"sqlForm"  => "department order by list ",
			"sqlId"    => "id",
			"sqlField" => "name",
			"name"     => $departmentName,
			"title"    => "当前部门",
			"class"    => $data['class'],
			"change"   => "getJob",
			"value"    => $data['department']['value'],
		));
		//当前职位
		if (empty($data['job']['name'])) {
			$jobName = "jobId";
		} else {
			$jobName = $data['job']['name'];
		}
		if (empty($data['department']['value'])) {
			$JobId = select(
				array("name" => $jobName, "title" => "当前职位", "class" => $data['class'], "change" => "getStaff")
			);
		} else {
			$JobId = idSelect(array(
				"sqlForm"  => "job where departmentId = '" . $data['department']['value'] . "' order by list ",
				"sqlId"    => "id",
				"sqlField" => "name",
				"name"     => $jobName,
				"title"    => "当前职位",
				"class"    => $data['class'],
				"change"   => "getStaff",
				"value"    => $data['job']['value'],
			));
		}
		//当前员工
		if (empty($data['staff']['name'])) {
			$staffName = "stid";
		} else {
			$staffName = $data['staff']['name'];
		}
		if (empty($data['staff']['title'])) {
			$staffTitle = "员工";
		} else {
			$staffTitle = $data['staff']['title'];
		}
		if (empty($data['staff']['value'])) {
			$stid = select(array("name" => $staffName, "title" => $staffTitle, "class" => $data['class'] ?? null));
		} else {
			$stid = idSelect(array(
				"sqlForm"  => "staff where jobId = '" . $data['job']['value'] . "' order by entryDay ",
				"sqlId"    => "stid",
				"sqlField" => "name",
				"name"     => $staffName,
				"title"    => "员工",
				"class"    => $data['class'],
				"value"    => $data['staff']['value'],
			));
		}
		//拼接下拉菜单
		$html  = "";
		$array = array($departmentId, $JobId, $stid);
		foreach ($array as $key => $select) {
			if ($key < $data['show']) {
				$html .= $select;
			}
		}
		//返回
		return $html;
	}

	/**
	 * 统计group by 的数据
	 *
	 * @param $sql
	 * @return mixed
	 */
	public function totalGroupNum($sql): mixed
	{
		$fullSql = "SELECT count(*) as total from ({$sql}) gropus";
		$result  = sqlFind($fullSql);
		if (isset($result[0]['total'])) {
			return $result[0]['total'];
		} else {
			if (static::is_null_array($result)) {
				return count(sqlFind($sql));
			}
			return 0;
		}
	}

	/**
	 * 导入获取数据
	 *
	 * @param string $fileName
	 * @param array  $format
	 * @return array
	 */
	public function importHead(string $fileName = 'file', $format = []): array
	{
		$tmp_name = $_FILES[$fileName]['tmp_name'];//临时文件名
		$nameUrl1 = $nameUrl2 = '';
		if (PHP_OS == 'Linux') {
			$nameUrl2 = $tmp_name;
		} elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
			//windows环境
			$num      = strripos($tmp_name, '\\');
			$nameUrl1 = substr($tmp_name, 0, $num); //缓存路径位置  C:\Users\Administrator\AppData\Local\Temp
			$nameUrl2 = substr($tmp_name, $num + 1);//文件名称  php1AE0.tmp
		}
		$config  = ['path' => $nameUrl1];
		$excel   = new \Vtiful\Kernel\Excel($config);
		$tempObj = $excel->openFile($nameUrl2)->openSheet();
		if (!empty($format)) {
			$tempObj = $tempObj->setType($format);
		}
		$result = $tempObj->getSheetData();
		return array_filter($result);
	}


	/**
	 * 组装sql
	 *
	 * @param $data
	 * @return string
	 */
	public function getSql($data): string
	{
		$where = '';
		if (empty($data['table'])) {
			$result = "数据库表名称为空";
		} else {
			//返回的字段
			if (empty($data['field'])) {
				if (!empty($data['sum'])) {
					$data['field'] = " sum(" . $data['sum'] . ") as " . $data['sum'];
				} else {
					$data['field'] = "*";
				}
			}
			//查询条件
			if (!empty($data['where'])) {
				$where = $data['where'];
			} elseif (!empty($data['single'])) {
				$where = $data['single'];
			}
			if (!empty($where)) {
				if (substr(trim($where), 0, 3) == "and" or substr(trim($where), 0, 8) == "order by" or empty($where)) {
					$where = " 1=1 " . $where;
				}
				$where = " where " . $where;
			}
			//执行
			$result = "SELECT " . $data['field'] . " FROM " . $data['table'] . $where;
		}
		//返回
		return $result;
	}

	/*分页
    $data = array(
        "table" => "要查询的表名称",
        "where" => "查询条件",
        "order" => "排序方式",
        "pageNum" => "每页显示记录条数",
        "buttonNum" => "要显示的分页按钮数量",
    );
    */
	public function page(array $data)
	{
		$data['field'] = $data['field'] ?? '*';
		$data['order'] = $data['order'] ?? '';
		$data['union'] = $data['union'] ?? '';
		//修正每页显示的条数
		if (empty($data['pageNum']) or preg_match(checkInteger, $data['pageNum']) == 0) {
			$data['pageNum'] = (int)para('numberOfPageItems');
		}
		//修正分页按钮数量
		if (empty($data['buttonNum']) or preg_match(checkInteger, $data['buttonNum']) == 0) {
			$data['buttonNum'] = 7;
		}
		if (str_contains(strtolower(trim($data['table'] . $data['where'] . $data['order'])), 'group')) {
			//group by 查询方式
			$sql    = $this->getSql(
				array(
					"table" => $data['table'],
					"field" => $data['field'],
					"where" => $data['where'] . ($data['order'] ? (" order by " . $data['order']) : ''),
				)
			);
			$sqlNum = $this->totalGroupNum($sql);
		} elseif ($data['union']) {
//			echo 2;
			//联表
			$sqlNum = static::total(array('sql' => "select ifnull(sum(a.num),0) as total from ({$data['union']}) as a")); //总条数
		} else {
			$sqlNum = static::total(array('table' => $data['table'], 'where' => $data['where'])); //总条数

		}
		$pageAll = is_numeric($sqlNum) ? ceil($sqlNum / $data['pageNum']) : exit($sqlNum);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               //总页数
		//修正当前页
		if ($this->get('page') > 1 and $this->get('page') <= $pageAll) {
			$pageNow = $this->get('page');
		} else {
			$pageNow = 1;
		}
		//判断要显示的第一个页码
		$pageCenter = ceil($data['buttonNum'] / 2);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               //底部分页按钮的居中页
		if ($pageNow <= $pageCenter) {//如果当前页小于等于居中页
			$pageFirst = 1;
		} elseif (($pageAll - $pageNow) <= $pageCenter) {  //如果当前页后面的页数小于等于居中页
			$pageFirst = $pageAll - $data['buttonNum'] + 1;//则把最后的几个页码显示出来
		} else {
			$pageFirst = $pageNow - $pageCenter;//如果当前页两边都有充足的页面，则居中显示
		}
		//拼接页码按钮
		$pageButton = "";
		for ($x = 0; $x < $data['buttonNum']; $x++) {
			$n = $pageFirst + $x;
			if ($n > 0 and $n <= $pageAll) {//$n可能小于零或大于总页数
				if ($n == $pageNow) {
					$c = " class='pageNow' ";
				} else {
					$c = "";
				}
				$pageButton .= "<li " . $c . " onclick=\"searchForm('" . $this->get('cla') . "','" . $this->get(
						'fun'
					) . "'," . $n . ")\">" . $n . "</li>\n";
			}
		}
		//分页下拉菜单
		$option = "";
		if ($pageAll > 0) {
			for ($x = 1; $x <= $pageAll; $x++) {
				if ($pageNow == $x) {
					$selected = " selected='selected' ";
				} else {
					$selected = "";
				}
				$option .= "<option value='" . $x . "' " . $selected . ">第" . $x . "页</option>";
			}
		} else {
			$option .= "<option value='1'>第1页</option>";
		}
		//分页html
		$pageLast         = $pageNow <= 1 ? 1 : $pageNow - 1;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             //上一页
		$pageNext         = $pageNow >= $pageAll ? $pageAll : $pageNow + 1;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               //下一页
		$result['button'] = "
		<div class='pageButton'>
			<ul>
				<li onclick=\"searchForm('" . $this->get('cla') . "','" . $this->get('fun') . "',1)\">第一页</li>
				<li onclick=\"searchForm('" . $this->get('cla') . "','" . $this->get('fun') . "'," . $pageLast . ")\">上一页</li>
				" . $pageButton . "
				<li onclick=\"searchForm('" . $this->get('cla') . "','" . $this->get('fun') . "'," . $pageNext . ")\">下一页</li>
				<li onclick=\"searchForm('" . $this->get('cla') . "','" . $this->get('fun') . "'," . $pageAll . ")\">最后一页</li>
			</ul>
			<select onchange=\"searchForm('" . $this->get('cla') . "','" . $this->get(
				'fun'
			) . "',this.value)\">" . $option . "</select>
		</div>
		";
		//数据库查询结果
		$sqlFirst = ($pageNow - 1) * $data['pageNum'];                                                     //当前页面开始位置
		$sqlTable = find(
			array(
				"table" => $data['table'],
				"field" => $data['field'],
				"where" => $data['where'] . ($data['order'] ? (" order by " . $data['order']) : '') . " limit " . $sqlFirst . "," . $data['pageNum'],
			)
		);
		if (is_array($sqlTable)) {
			$result['sql']     = $sqlTable['sql'];
			$result['array']   = $sqlTable['array'];
			$result['fullSql'] = $this->interceptString($result['sql'], 'limit');
		} else {
			$result['sql']     = $sqlTable;
			$result['fullSql'] = $this->interceptString($result['sql'], 'limit');
			$result['array']   = [];
		}
		//提示
		$result['hint'] = "
		<span class='pageHint'>
			共找到" . $sqlNum . "条数据&nbsp;&nbsp;
			第" . $pageNow . "页/
			共" . $pageAll . "页
		</span>
		";
		//返回
		return $result;
	}

	/**
	 * 截取指定字符串之前的字符
	 *
	 * @param $str       string 字符串
	 * @param $searchStr string 指定字符
	 * @return string
	 */
	public function interceptString(string $str, string $searchStr): string
	{
		return str_replace(strchr($str, $searchStr), "", $str);
	}

	/*头部*/
	public function adHeader(array $onion)
	{
		$url = para("name");
		array_unshift($onion, $this->control['name']);
		foreach ($onion as $value) {
			$url .= "&nbsp;>&nbsp;" . $value . "";
		}
		$html = "
        <div id='header'>
            <div id='renovate' onclick='window.location.reload()'><img title='刷新' src='" . root . "img/control/renovate.svg'></div>
            <div class='onion'>" . $url . "</div>
        </div>
		<div id='body'>
		";
		return $html;
	}

	/*底部*/
	public function adFooter()
	{
		$html = "
				</div>
			</body>
		</html>
		";
		return $html;
	}


    /**
     * 查询条件
     *
     * @param string $html 查询表单
     * @param string|null $type 类型
     * @param string $otherButton
     * @return string
     */
	public function search(string $html, string $type = null, $otherButton = '',$cla='',$fun='')
	{
		//异步调用数据的函数名称
		$fun   = $fun?:$this->get('fun') . "Search";
		$cla   = $cla?:$this->get('cla');

		$light = '';
		if ($type === null) {
			$light = '<div class="space bg-light-grey"></div>';
		} elseif ($type == 'menu') {
			$light = '<style>#homeSearchHtml{padding: 0;}</style>';
		}
        if ($otherButton === 'no'){
            $light = '';
        }
		$hide        = $otherButton === 'no' ? 'hide' : '';
		$otherButton = $otherButton === 'no' ? '' : $otherButton;

		return "
		<div class='search $hide'>
			<form name='" . $fun . "Form' onsubmit=\"return searchFormSub('" . $cla . "','" . $fun . "')\">
				" . $html . "
				<input class='layer_search_button' type='submit' value='查询'>
				{$otherButton}
			</form>
		</div>
        $light
		<div id='" . $fun . "Html'>数据查询中。。。</div>
		<script>$(function(){searchForm('" . $cla . "','" . $fun . "',1)});</script>
		";
	}

	/**
	 * 页面权限检查
	 *
	 * @return array
	 */
	public function homePower(): array
	{
		//页面名称
		$key  = '';
		$name = '';
		if (empty($this->get('cla'))) {
			$warn = "类名称为空";
		} elseif (empty($this->get('fun'))) {
			$warn = "类的方法名称为空";
		} else {
			foreach ($this->powerAll as $all) {
				foreach ($all as $oneName => $oneArray) {
					unset($oneArray['attribute']);
					foreach ($oneArray as $twoKey => $twoArray) {
						if (isset($twoArray['cla']) && ($twoArray['cla'] == $this->get(
									'cla'
								) and $twoArray['fun'] == $this->get('fun'))) {
							$key  = $twoKey;
							$name = $twoArray['name'];
						} elseif (empty($twoArray['cla']) and empty($twoArray['fun']) and $this->get(
								'cla'
							) == $twoKey) {
							$key  = $twoKey;
							$name = $twoArray['name'];
						}
					}
				}
			}
		}
		//权限判断
		if (empty($key)) {
			$warn = "需要打开的页面名称为空";
		} elseif (!in_array($key, array_keys($this->controlPower))) {
			$warn = "你没有打开《" . $name . "》页面的权限";
		}
		//跳转
		if (!empty($warn)) {
			$_SESSION['warn'] = $warn;
			header("location:" . root . "control/adIndex.html?cla=homepage&fun=home");
			exit(0);
		}
		//返回
		return ["key" => $key, "name" => $name];
	}

	/**
	 * 搜索框
	 *
	 * @param $data
	 * @return string
	 */
	public static function searchText($data): string
	{
		$attribute = $js = "";
		if (isset($data['id'])) {
			$attribute .= " id='" . $data['id'] . "' ";
		} elseif (array_key_exists("laydate", $data)) { //如果存在laydate键名
			$id        = suiji();
			$attribute .= " id='" . $id . "' ";
			$json      = "";
			foreach ((array)$data['laydate'] as $key => $value) {
				if (in_array($key, ['done', 'ready', 'change', 'mark'])) {
					$json .= "," . $key . ":" . $value . "";
				} else {
					$json .= "," . $key . ":'" . $value . "'";
				}
			}
			$js = "<script>$(function(){laydate.render({elem:'#" . $id . "'" . $json . ", trigger:'click'});});</script>";
		}
		if (isset($data['title']) && $data['title']) {
			$attribute .= "  placeholder='" . $data['title'] . "' title='" . $data['title'] . "' ";
		}
		if (isset($data['value']) && mb_strlen($data['value'], 'utf8') > 0) {
			$attribute .= " value='" . $data['value'] . "' ";
		}
		$data['class'] = $data['class'] ?? '';
		$data['class'] = "search-text " . $data['class'];
		if (isset($data['unit'])) {//单位
			$data['class'] .= " layui-input form-control";
		}
		if ($data['class']) {
			$attribute .= " class='" . $data['class'] . "' ";
		}
		// 自定义data 参数
		if (isset($data['data']) && is_array($data['data'])) {
			foreach ($data['data'] as $key => $value) {
				$key       = trim($key);
				$value     = trim($value);
				$attribute .= " data-{$key}='{$value}' ";
			}
		}
		// 支持的类型
		$keys  = ['blur', 'change', 'keyup'];
		$array = array_intersect($keys, array_keys($data));
		foreach ($array as $key) {
			$temp = explode(',', $data[$key]);
			// 统计个数
			$length    = count($temp);
			$attribute .= ' on' . $key . '="' . $temp[0] . "(this";
			if ($length > 1) {
				for ($i = 1; $i < $length; $i++) {
					$temp[$i]  = trim(str_replace(['\'', '"'], '', $temp[$i]));
					$attribute .= ", '$temp[$i]'";
				}
			}
			$attribute .= ')"';
		}
		$type  = $data['type'] ?? 'text';
		$other = $data['other'] ?? '';
		$html  = "<input type='{$type}' name='{$data['name']}' autocomplete='off' " . $attribute . $other . ">" . $js;
		if (isset($data['unit'])) {
			//带单位的输入框
			$html = "<div class='input-group'>" . $html . " <span class='input-group-addon'>{$data['unit']}</span></div>";
		} elseif (isset($data['search'])) {
			$html = "<span class='right interval' >" . $html . "<span onclick=\"{$data['click']}\" class='background-color-gray'><img alt='' src='" . root . "img/control/search.svg'></span></span>";
		}
		$html .= <<<efo
<style>
  .search-text{
     height: 19px;padding: 2px 4px;border-top-left-radius:2px;border-bottom-left-radius:2px;
  }
  .background-color-gray{
    margin: 0;padding:3px 10px;cursor: pointer;
  }
  .interval{
    margin-right: 10px;
  }
</style>
efo;

		return $html;
	}

	/*导入按钮
    $data = array(
        "title" => "按钮标题",
        "fun" => "导入分析函数",
    );
    */
	public function upButton($data): string
	{
		//表单名称
		$form = self::getId() . "UpForm";

		//HTML内容
		return <<<eof
<span class='spanButton' onclick="document.{$form}.file.click()">{$data['title']}</span>
<form name='{$form}'  class='hide' method='post' enctype='multipart/form-data' action='{$this->root}control/adIndex.html?cla={$this->get('cla')}&fun={$data['fun']}'>
			<input name='file' type='file' onchange='document.{$form}.submit()'>
		</form>
eof;
	}

	/**
	 * 入口页函数
	 *
	 * @param string $html "查询表单";
	 * @return string
	 */
	public function homeFun($html)
	{
		//页面权限
		$homePower = $this->homePower();
		//洋葱皮
		foreach ($this->powerAll as $oneKey => $twoArray) {
			foreach ($twoArray as $twoKey => $threeArray) {
				unset($threeArray['attribute']);
				if (array_key_exists($homePower['key'], $threeArray)) {
					$oneName   = $oneKey;
					$twoName   = $twoKey;
					$threeName = $threeArray[$homePower['key']]['name'];
					break;
				}
			}
		}
		$onion = array($oneName, $twoName, $threeName);
		//返回
		return head("ad") . $this->adHeader($onion) . $html . warn() . $this->adFooter();
	}

	/*详情页~页卡
    $data = array(
        "id" => "切换内部页卡和当前提交表单时的ID",
        "title" => "洋葱皮最后一级导航，有onion参数时可不填本参数",
        "button" => "当前表单提交按钮标题",
        "onion" => "定义全部洋葱皮导航，非必填",
        "menu" => array(
            "菜单关键词" => "菜单标题",  //需要调用的函数在当前类时的简写
            "菜单关键词" => array(     //需要调用其他类方法时的写法
                "name" => "菜单标题",
                "cla" => "类名称",
                "fun" => "类的方法名称",
            ),

        ),
        "power" =>  页面权限
    );
    */
	public function tab(array $data)
	{
		$html = $form = "";
		//页面权限
		if (isset($data['power']) && $data['power'] !== false) {
			$this->homePower();
		}
		//生成导航
		if (isset($data['menu']) && $data['menu']) {
			$li = "";
			foreach ($data['menu'] as $key => $value) {
				if (empty($li)) {
					$hover = " class='pageMenuHover' ";
				} else {
					$hover = "";
				}
				if (is_array($value)) {
					$tabName   = $value['name'];//页卡中文名称
					$className = $value['cla']; //调用的类的名称
					$fun       = $value['fun']; //调用的方法的名称
				} else {
					$tabName   = $value;
					$className = $this->get('cla');
					$fun       = $key;
				}
				$li .= "<li pageMenu='" . $fun . "' onclick=\"detailTab('" . $className . "','" . $fun . "','" . $data['id'] . "')\" " . $hover . ">" . $tabName . "</li>";
				//如果GET menu为当前页卡
				if ($this->get('menu') == $fun) {
					$html .= "<script>$(function(){detailTab('" . $className . "','" . $fun . "','" . $data['id'] . "')});</script>";
				}
			}
			$html .= "
			<div id='pageMenu'>
				<ul>" . $li . "</ul>
                <div class='space bg-light-grey'></div>
				<div class='clear'></div>
			</div>
			";
		}

		//洋葱皮
		if (!isset($data['onion']) || !$data['onion']) {
			$data['onion'] = [];
			$oneName       = $twoName = $threeName = $threeHref = '';
			//洋葱皮
			foreach ($this->powerAll as $oneKey => $twoArray) {
				foreach ($twoArray as $twoKey => $threeArray) {
					unset($threeArray['attribute']);
					$className = $this->get('cla');
					if (array_key_exists($className, $threeArray)) {
						//三级导航数组
						$threeArray = $threeArray[$className];
						//三级导航链接
						if (!isset($threeArray['cla']) or !$threeArray['cla'] or !isset($threeArray['fun']) or !$threeArray['fun']) {//如果没有定义类或函数名称，则使用模块名称作为类名称
							$iframeHref = root . "control/adIndex.html?cla=" . $className . "&fun=home";
						} else {
							$iframeHref = root . "control/adIndex.html?cla=" . $threeArray['cla'] . "&fun=" . $threeArray['fun'];
						}
						// 一级菜单
						$oneName = $oneKey;
						// 二级菜单
						$twoName   = $twoKey;
						$threeName = $threeArray['name'];
						//三级导航
						$threeHref = "<span title='点击返回列表页' class='one' onclick=\"newIframe('" . $threeArray['name'] . "','" . $iframeHref . "')\">" . $threeArray['name'] . "</span>";
						break;
					}
				}
			}
			// 四级
			// $fourName = $data['title'] ?? $threeName.'详情';
			$fourName      = $threeName . '详情';
			$data['onion'] = [$oneName, $twoName, $threeHref, $fourName];
		}
		//定义初始页卡的表单
		if (isset($data['tr']) && is_array($data['tr']) and count($data['tr']) > 0) {
			//表单提交
			if (empty($data['sub'])) {
				$sub = "subForm('" . $this->get('fun') . "Form',root+'control/adIndex.html?cla=" . $this->get(
						'cla'
					) . "&fun=" . $this->get('fun') . "Edit')";
			} else {
				$sub = $data['sub'];
			}
			//生成表单
			$form = "
			<form name='" . $this->get('fun') . "Form'>
				" . $this->tableEdit($data['tr']) . "
				<input name='id' type='hidden' value='" . getVal($data, 'id') . "'>
				<div onclick=\"" . $sub . "\" class='formButton'>" . $data['button'] . "</div>
			</form>
			";
		}
		//第一个页卡的关键词
		if (empty($data['menu'])) {
			$pageDiv = $this->get('fun');
		} else {
			$pageDiv = key($data['menu']);
		}
		//生成页卡
		$html           .= "
		<div class='pageDiv' pageDiv='" . $pageDiv . "'>
			" . $form . ($data['html'] ?? null) . clear . "
		</div>";
		$data['header'] = $data['header'] ?? '';
		if ($data['header'] === false) {
			return $html;
		}
		//返回
		return head("ad") . $this->adHeader($data['onion']) . $html . warn() . $this->adFooter();
	}

	/*弹出层
    $data = array(
        "title" => "标题",
        "height" => "高度",
        "width" => "宽度",
        "zindex" => "弹出层堆叠顺序",//非必填
        "html" => "内容",
    );
    */
	public function layer($data)
	{
		$dibianZ = $winZ = '';
		//弹出层HTML ID
		$json['id'] = $this->get('cla') . ucwords($this->get('fun'));
		//定义弹出层堆叠顺序
		if (!empty($data['zindex'])) {
			$dibianZ = "z-index:" . ($data['zindex'] - 1) . ";";
			$winZ    = "z-index:" . $data['zindex'] . ";";
		}
		//默认宽度，此为经调试后弹出层双列表单的最优宽度
		if (empty($data['width'])) {
			$data['width'] = 800;
		}

		if (empty($data['winFix'])) {
			$winFix = "class='winAuto'";
		} else {
			$winFix = '';
		}
		//弹出层框架
		$json['html'] = "
		<div class='dibian' style='" . $dibianZ . "'></div>
		<div class='win animated fadeInUp' style='height:" . $data['height'] . "px; width:" . $data['width'] . "px; margin:-" . ceil(
				$data['height'] / 2
			) . "px 0px 0px -" . ceil($data['width'] / 2) . "px;" . $winZ . "'>
			<div class='winTitle'>" . $data['title'] . "<span onclick=\"$('#" . $json['id'] . "').hide()\" class='winClose'>×</span></div>
			<div {$winFix} style='height:" . ($data['height'] - 40) . "px;'>" . $data['html'] . "</div>
		</div>
		";
		//返回
		return json_encode($json, 320);
	}

	/**
	 * 获取当前员工的当前部门和所有上级部门，当前职位，当前员工ID组合
	 */
	public function staffCombination($isString = false, $stid = ''): array|string
	{
		if ($stid) {
			$staff  = query('staff', "stid = '$stid'");
			$result = [
				$stid,
				$staff['jobId'],
			];
			$job    = query('job', "id = '$staff[jobId]'");
			$this->departmentCom($job['departmentId'], $departmentId);
		} else {
			$result = [
				self::$stid,
				$this->controlJob['id'],
			];
			$this->departmentCom($this->controlJob['departmentId'], $departmentId);
		}

		$result = array_merge($result, $departmentId);
		return $isString ? implode(',', $result) : $result;
	}

	/**
	 * 获取部门集合
	 */
	private function departmentCom($departmentId, &$arr)
	{
		$arr[]            = $departmentId;
		$department       = query('department', "id = '$departmentId'");
		$departmentParent = query('department', "id = '$department[pid]'");
		if (!empty($departmentParent['id'])) {
			$this->departmentCom($departmentParent['id'], $arr);
		}
		return $arr;
	}

	/**
	 * loading
	 *
	 * @return string
	 */
	public function loadHtml(): string
	{
		return <<<eof
         <div id='loading' style='width: 100%;height: 100%;display: none'>
             <div class='dibian' style='opacity: 0.1;'></div>
                <div class="loader loader-1" style="z-index: 999;position: absolute;top: 45%;left: 50%;transform: translate(-50%, -100%);">
                <div class="loader-outter"></div>
                <div class="loader-inner"></div>
             </div>
         </div>
eof;
	}


	/**
	 * 获取会员中心列表
	 *
	 * @return string
	 */
	public function getUserBox(): string
	{
		$avatar  = $this->control['ico'];
		$temp    = '<ul class="userList">';
		$helpUrl = para('helpUrl');
		$array   = [
			[
				'avatar' => root . $avatar,
				'click'  => "newIframe('个人档案', '{$this->root}control/adIndex.html?cla=my&fun=home')",
			],
			[
				'title' => '我的待办',
				'mark'  => $this->getMarkNum('待办'),
				'click' => "newIframe('我的待办', '{$this->root}control/adIndex.html?cla=backlog&fun=home')",
			],
			[
				'title' => '我的消息',
				'mark'  => $this->getMarkNum('消息'),
				'click' => "newIframe('我的待办', '{$this->root}control/adIndex.html?cla=message&fun=home')",
			],
			[
				'title' => '帮助文档',
				'click' => "window.open('" . $helpUrl . "')",
			],
			[
				'title' => '系统日志',
				'click' => "newIframe('系统日志', '{$this->root}control/adIndex.html?cla=log&fun=home')",
			],
			[
				'title' => '退出登录',
				'href'  => $this->root . 'control/adIndex.html?cla=login&fun=out',
			],
		];
		foreach ($array as $key => $value) {
			$mark  = isset($value['mark']) && $value['mark'] ? '<span class="corner-marks">' . $value['mark'] . '</span>' : '';
			$click = isset($value['click']) && $value['click'] ? 'onclick="' . $value['click'] . '"' : '';
			$href  = isset($value['href']) && $value['href'] ? 'href="' . $value['href'] . '"' : '';
			if ($key == 0) {
				$temp .= '<li class="user-avatar" ' . $click . '><a ' . $href . '><img class="user-avatar-img" src="' . $value['avatar'] . '"><span class="user-avatar-title">' . self::$user['name'] . '</a></li>';
			} else {
				$temp .= '<li ' . $click . '><a ' . $href . '>' . $value['title'] . $mark . '</a></li>';
			}
		}
		$temp .= '</ul>';
		return $temp;
	}

	/**
	 * 分转元
	 */
	public static function centToYuan($money): float|int
	{
		return $money / self::baseUnit;
	}

	/**
	 * 元转分
	 */
	public static function yuanToCent($money): float|int
	{
		return $money * self::baseUnit;
	}

	/**
	 * 对比获取一级菜单
	 *
	 * @return array
	 */
	public static function getMenuHandle(): array
	{
		$userKeys = (array)array_keys(self::getUserPower());
		$array    = [];
		foreach ($GLOBALS['powerAll'] as $oneName => $twoArray) {
			foreach ($twoArray as $twoName => $threeArray) {
				$data = array_keys($threeArray);
				$res  = array_intersect($data, $userKeys);
				if (count($res) > 0) {
					$array[] = $oneName;
					break;
				}
			}
		}
		return $array;
	}

	/**
	 * 获取菜单
	 *
	 * @return string
	 */
	public static function getMenu(): string
	{
		$nowMenu = self::$user['menu'] ?? '个人中心';
		$array   = self::getMenuHandle();
		// 计算
		$radix  = 7;
		$col    = ceil(count($array) / $radix);
		$width  = $col * 150 - ($col * 4);
		$height = count($array) > $radix ? $radix * 35 : count($array) * 35;
		$x      = 1;
		$temp   = '<ul class="primaryMenu" style="width:' . $width . 'px;height:' . $height . 'px;">';
		$flag   = true;
		foreach ($array as $key => $value) {
			// 是否标记
			if ($value == $nowMenu) {
				$clipSel = 'clip-selected';
				$liSel   = 'selected';
			} else {
				$clipSel = '';
				$liSel   = '';
			}
			if ($flag) {
				$key  += 1;
				$temp .= '<li data-key=' . $key . ' class="' . $liSel . '"><span>' . $value . '</span><img src="' . root . 'img/control/clip.svg" class="clip ' . $clipSel . '" data-title="' . $value . '"></li>';
			}
			if ($key && ceil($key / $radix) - 1 >= 1) {
				$right = $x * 150 - $x;
				$temp  .= '<hr class="interval-line-right" style="left:' . $right . 'px;height:' . $height . 'px">';
				$x     += 1;
			}
		}
		$temp .= "</ul>";
		return $temp;
	}

	/*返回*/
	public function adIndexHtml()
	{
		if ($this->get('cla') == "login") {
			if (empty($this->warn)) {
				header("location:" . root . "pad/index.html?cla=dispatch&fun=home");
				exit(0);
			}
			$html = $this->login();
		} elseif (!empty($this->warn)) {//如果存在登录提示
			if (empty($this->get('cla'))) {//如果是框架级刷新，则跳转至登录页
				$_SESSION['warn'] = $this->warn;
				header("location:" . root . "pad/index.html?cla=login");
				exit();
			} else {//如果是内页请求，包括异步请求，则返回json数据
				$json['warn'] = $this->warn;
				$html         = json_encode($json, 320);
			}
		} elseif ($this->get('cla') == "pasWarn") {
			$html = $this->pasWarn();
		} else {
		    $cla = $this->get('cla')?:'dispatch';
		    $fun = $this->get('fun')?:'home';
            //定义名称
            $className = $cla . "Class";                  //类名称
            $classUrl  = serverRoot . "pad/" . $className . ".php";//类文件路径
            //获取类文件
            if (!file_exists($classUrl)) {
                $html = $className . '开发中11';
            } elseif (empty($fun)) {
                $html = "类的方法名称为空";
            } elseif (!method_exists(__NAMESPACE__ . '\\' . $className, $fun)) {
                $html = $className . "类中未找到方法" . $fun;
            } else {

                //实例化对象
                $class = new (__NAMESPACE__ . '\\' . $className)();
                //打印结果
                $html = $class->$fun();

            }
		}
		//返回
		return $html;
	}
}
//实例化对象
$padIndexClass = new indexClass();
//打印结果
echo $padIndexClass->adIndexHtml();
